### Install phpSPO using Composer Source: https://github.com/vgrem/phpspo/blob/master/README.md This snippet shows how to install the phpSPO library using Composer, the standard package manager for PHP. It includes the composer require command and an example of how to include the autoloader in your project. ```sh composer require vgrem/php-spo ``` ```json { "require": { "vgrem/php-spo": "^3" } } ``` ```php require_once '/path/to/your-project/vendor/autoload.php'; ``` -------------------------------- ### Get SharePoint Web Properties using PHP Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves specific properties of a SharePoint web site, including its title, description, URL, creation date, and language. This script requires client credentials and the site URL. The fetched properties are then printed to the console. ```php withCredentials($credentials); $web = $ctx->getWeb() ->select(["Title", "Description", "Url", "Created", "Language"]) ->get() ->executeQuery(); echo "Title: " . $web->getTitle() . PHP_EOL; echo "Description: " . $web->getDescription() . PHP_EOL; echo "URL: " . $web->getUrl() . PHP_EOL; echo "Created: " . $web->getCreated()->format('Y-m-d H:i:s') . PHP_EOL; echo "Language: " . $web->getLanguage() . PHP_EOL; ?> ``` -------------------------------- ### Retrieve My Drive URL via OneDrive API (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md This example shows how to get the 'My Drive' URL using the OneDrive API in PHP. It involves authentication and then querying the drive object. ```php use Office365\GraphServiceClient; use Office365\Runtime\Auth\AADTokenProvider; use Office365\Runtime\Auth\UserCredentials; function acquireToken() { $tenant = "{tenant}.onmicrosoft.com"; $resource = "https://graph.microsoft.com"; $provider = new AADTokenProvider($tenant); return $provider->acquireTokenForPassword($resource, "{clientId}", new UserCredentials("{UserName}", "{Password}")); } $client = new GraphServiceClient("acquireToken"); $drive = $client->getMe()->getDrive()->get()->executeQuery(); print $drive->getWebUrl(); ``` -------------------------------- ### Get Planner Tasks Report using PHP Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves all planner plans and tasks associated with a specific Microsoft 365 group. This script requires user credentials and the group name. It outputs a JSON-formatted report containing plan IDs, titles, and details of each task, including assignments and timestamps. ```php getGroups() ->filter("displayName eq '$groupName'") ->get() ->executeQuery(); if (count($groups->getData()) === 0) { throw new Exception("Group '$groupName' not found"); } // Get all plans in the group $plans = $groups[0]->getPlanner()->getPlans()->get()->executeQuery(); $allPlansWithTasks = []; /** @var PlannerPlan $plan */ foreach ($plans as $plan) { $tasks = $plan->getTasks()->get()->executeQuery(); $planData = [ 'plan_id' => $plan->getId(), 'plan_title' => $plan->getTitle(), 'tasks' => [] ]; /** @var PlannerTask $task */ foreach ($tasks as $task) { $planData['tasks'][] = [ 'task_id' => $task->getId(), 'task_title' => $task->getTitle(), 'task_assignments' => $task->getAssignments(), 'task_created' => $task->getCreatedDateTime(), 'task_completed' => $task->getCompletedDateTime(), ]; } $allPlansWithTasks[] = $planData; } echo json_encode($allPlansWithTasks, JSON_PRETTY_PRINT); ?> ``` -------------------------------- ### List Calendar Events in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves calendar events from a user's calendar using the Office365 library. It fetches events with specified fields, ordered by start time, and limited to the top 20. The output includes event subject, start time, and location. ```php getMe()->getCalendar()->getEvents() ->select(["subject", "start", "end", "location"]) ->orderBy("start/dateTime") ->top(20) ->get() ->executeQuery(); /** @var Event $event */ foreach ($events as $event) { echo "Event: " . $event->getSubject() . PHP_EOL; echo "Start: " . $event->getStart()->getDateTime() . PHP_EOL; echo "Location: " . $event->getLocation()->getDisplayName() . PHP_EOL; echo "---" . PHP_EOL; } ?> ``` -------------------------------- ### Get OneDrive Information in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves the current user's OneDrive information, including drive name, web URL, drive type, and quota details (total and used space). Requires the Office365 library and authentication credentials. Space is displayed in GB. ```php getMe()->getDrive()->get()->executeQuery(); echo "Drive Name: " . $drive->getName() . PHP_EOL; echo "Web URL: " . $drive->getWebUrl() . PHP_EOL; echo "Drive Type: " . $drive->getDriveType() . PHP_EOL; echo "Total Space: " . number_format($drive->getQuota()->getTotal() / (1024*1024*1024), 2) . " GB" . PHP_EOL; echo "Used Space: " . number_format($drive->getQuota()->getUsed() / (1024*1024*1024), 2) . " GB" . PHP_EOL; ?> ``` -------------------------------- ### Get SharePoint Folder by Path (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Accesses a SharePoint folder using its server-relative URL. This PHP snippet uses the Office365 SDK and returns the folder's name, URL, and item count if found, otherwise indicates that the folder was not found. ```php withCredentials($credentials); $folderUrl = "/sites/{site}/Shared Documents/Projects/2025"; $folder = $ctx->getWeb()->getFolderByServerRelativeUrl($folderUrl)->get()->executeQuery(); if ($folder->exists()) { echo "Folder: " . $folder->getName() . PHP_EOL; echo "URL: " . $folder->getServerRelativeUrl() . PHP_EOL; echo "Item count: " . $folder->getItemCount() . PHP_EOL; } else { echo "Folder not found" . PHP_EOL; } ?> ``` -------------------------------- ### Generate Self-Signed Certificate Keys (OpenSSL) Source: https://github.com/vgrem/phpspo/wiki/Granting-access-via-Azure-AD-App‐Only-with-Certificate These commands use OpenSSL to generate a private key and a self-signed X.509 certificate. The private key is used for authentication, and the public certificate is uploaded to Azure AD. Ensure OpenSSL is installed on your system. ```bash openssl genrsa -out private.key 2048 openssl req -new -x509 -key private.key -out publickey.cer -days 365 ``` -------------------------------- ### Get Microsoft Team Channels (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves all channels associated with a specific Microsoft Team. This PHP code uses the Office365 PHP SDK and the Microsoft Graph API, requiring the team ID for the lookup. It outputs the display name and description for each channel. ```php getTeams()->getById($teamId); $channels = $team->getChannels()->get()->executeQuery(); /** @var Channel $channel */ foreach ($channels as $channel) { echo "Channel: " . $channel->getDisplayName() . PHP_EOL; echo "Description: " . $channel->getDescription() . PHP_EOL; echo "---" . PHP_EOL; } ?> ``` -------------------------------- ### Create Modern SharePoint Site using PHP Source: https://context7.com/vgrem/phpspo/llms.txt Creates a new modern SharePoint communication site. This script requires client credentials and tenant information. It defines the site name, admin email, and classification, then outputs the success status and the URL of the newly created site. Error handling is included for failed creation. ```php withCredentials($credentials); $result = $ctx ->getSiteManager() ->create( "project-phoenix-site", "admin@domain.com", "Low Business Impact" ) ->executeQuery(); echo "Site created successfully" . PHP_EOL; echo "Site URL: " . $result->getValue()->SiteUrl . PHP_EOL; } catch (Exception $e) { echo 'Site creation failed: ' . $e->getMessage() . PHP_EOL; } ?> ``` -------------------------------- ### Download SharePoint File as Binary Source: https://context7.com/vgrem/phpspo/llms.txt Downloads a file from SharePoint and returns its content as binary data. This is suitable for smaller files. The downloaded content is then saved to a temporary local file. Requires the Office365 client library. ```php withCredentials($credentials); $sourceFileUrl = "/sites/{site}/Shared Documents/report.pdf"; $fileContent = File::openBinary($ctx, $sourceFileUrl); $localFileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "downloaded-report.pdf"; file_put_contents($localFileName, $fileContent); echo "File downloaded: $localFileName" . PHP_EOL; echo "Size: " . strlen($fileContent) . " bytes" . PHP_EOL; ``` -------------------------------- ### Create Microsoft Team (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md Demonstrates how to create a Microsoft Team using delegated permissions via the Graph API. It requires the Office365 PHP SDK, AADTokenProvider for authentication, and the desired team name. ```php use Office365\GraphServiceClient; use Office365\Runtime\Auth\AADTokenProvider; use Office365\Runtime\Auth\UserCredentials; function acquireToken() { $tenant = "{tenant}.onmicrosoft.com"; $resource = "https://graph.microsoft.com"; $provider = new AADTokenProvider($tenant); return $provider->acquireTokenForPassword($resource, "{clientId}", new UserCredentials("{UserName}", "{Password}")); } $client = new GraphServiceClient("acquireToken"); $teamName = "My Sample Team"; $newTeam = $client->getTeams()->add($teamName)->executeQuery(); ``` -------------------------------- ### Authenticate SharePoint with Client Certificate in PHP Source: https://github.com/vgrem/phpspo/blob/master/README.md This PHP snippet illustrates authentication with SharePoint using an app principal and a client certificate. It requires the tenant name, client ID, the content of the private key file, and the certificate's thumbprint. The `ClientContext` is configured with these details. ```php use Office365\Runtime\Auth\ClientCredential; use Office365\SharePoint\ClientContext; $tenant = "{tenant}.onmicrosoft.com"; //tenant id or name $privateKeyPath = "-- path to private.key file--" $privateKey = file_get_contents($privateKeyPath); $ctx = (new ClientContext("{siteUrl}"))->withClientCertificate( $tenant, "{clientId}", $privateKey, "{thumbprint}"); ``` -------------------------------- ### Authenticate SharePoint with Client Credentials in PHP Source: https://github.com/vgrem/phpspo/blob/master/README.md This PHP code demonstrates how to authenticate with SharePoint Online or On-Premises using app principal with client credentials. It requires the client ID, client secret, and site URL. The `ClientContext` is initialized with these credentials. ```php use Office365\Runtime\Auth\ClientCredential; use Office365\SharePoint\ClientContext; $credentials = new ClientCredential("{clientId}", "{clientSecret}"); $ctx = (new ClientContext("{siteUrl}"))->withCredentials($credentials); ``` -------------------------------- ### Connect to SharePoint Online using PHP Source: https://github.com/vgrem/phpspo/wiki/How-to-connect-to-SharePoint-Online-and-and-SharePoint-2013-2016-2019-on-premises--with-app-principal This PHP code demonstrates how to establish a connection to SharePoint Online using app-only credentials. It utilizes the Office365 PHP SDK to authenticate and retrieve the current user's login name. ```php require_once __DIR__ . '/../vendor/autoload.php'; use Office365\Runtime\Auth\ClientCredential; use Office365\SharePoint\ClientContext; $credentials = new ClientCredential($clientId, $clientSecret); $ctx = (new ClientContext($webUrl))->withCredentials($credentials); $whoami = $ctx->getWeb()->getCurrentUser(); $ctx->load($whoami); $ctx->executeQuery(); print $whoami->getLoginName(); ``` -------------------------------- ### Create SharePoint List Item (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md Demonstrates how to create a new list item in a SharePoint list. It requires the Office365 PHP SDK, valid SharePoint credentials, and the list title. The item is created with specified properties. ```php use Office365\SharePoint\ClientContext; use Office365\Runtime\Auth\ClientCredential; $credentials = new ClientCredential("{client-id}", "{client-secret}"); $client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials); $list = $client->getWeb()->getLists()->getByTitle("Tasks"); $itemProperties = array('Title' => 'Order Approval', 'Body' => 'Order approval task'); $item = $list->addItem($itemProperties)->executeQuery(); print "Task {$item->getProperty('Title')} has been created.\r\n"; ``` -------------------------------- ### PHP: SharePoint Fluent API for List Operations Source: https://context7.com/vgrem/phpspo/llms.txt Demonstrates the use of a fluent API in PHP to interact with SharePoint lists. It shows how to retrieve, filter, order, and limit list items, as well as how to add a new item to a list. This approach allows for chaining multiple operations in a readable manner. Requires the 'vendor/autoload.php' and Office365 SDK. ```php withCredentials($credentials); // Fluent API: read items $items = $ctx->getWeb() ->getLists() ->getByTitle("Tasks") ->getItems() ->select(["Title", "Status", "Priority"]) ->filter("Status ne 'Completed'") ->orderBy("Priority", false) ->top(10) ->get() ->executeQuery(); /** @var ListItem $item */ foreach ($items as $item) { echo $item->getProperty('Title') . " [" . $item->getProperty('Priority') . "]" . PHP_EOL; } // Fluent API: create item $newItem = $ctx->getWeb() ->getLists() ->getByTitle("Tasks") ->addItem(['Title' => 'New Task', 'Priority' => 'High']) ->executeQuery(); echo "Created item ID: " . $newItem->getProperty('Id') . PHP_EOL; ``` -------------------------------- ### Download Files from OneDrive in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Downloads files from a user's OneDrive root directory. It fetches up to 10 children, checks if they are files, and then downloads them to the system's temporary directory. Requires the Office365 library and authentication. ```php getMe()->getDrive()->getRoot()->getChildren()->top(10)->get()->executeQuery(); /** @var DriveItem $item */ foreach ($items as $item) { if ($item->isFile()) { echo "Downloading: " . $item->getName() . PHP_EOL; $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $item->getName(); $fh = fopen($fileName, 'w+'); $item->download($fh)->executeQuery(); fclose($fh); echo "Downloaded to: $fileName" . PHP_EOL; } } ?> ``` -------------------------------- ### Authenticate SharePoint API with Client Certificate (PHP) Source: https://github.com/vgrem/phpspo/wiki/Granting-access-via-Azure-AD-App‐Only-with-Certificate This PHP code snippet demonstrates how to initialize a `ClientContext` for SharePoint using client certificate credentials. It requires the SharePoint site URL, tenant ID, client ID, private key content, and certificate thumbprint. The `withClientCertificate` method handles the authentication flow. ```php use Office365\SharePoint\ClientContext; $siteUrl = "https://contoso.sharepoint.com"; //site or web absolute url $tenant = "contoso.onmicrosoft.com"; //tenant id or name $thumbprint = "--thumbprint goes here--"; $clientId = "--client app id goes here"; $privateKetPath = "-- path to private.key file--" $privateKey = file_get_contents($privateKetPath); $ctx = (new ClientContext($siteUrl))->withClientCertificate( $tenant, $clientId, $privateKey, $thumbprint); $whoami = $ctx->getWeb()->getCurrentUser()->get()->executeQuery(); print $whoami->getLoginName(); ``` -------------------------------- ### Download SharePoint File as Stream Source: https://context7.com/vgrem/phpspo/llms.txt Downloads large files from SharePoint efficiently by using a stream. The file content is written directly to a file handle, avoiding loading the entire file into memory. Requires the Office365 client library. ```php withCredentials($credentials); $sourceFileUrl = "/sites/{site}/Shared Documents/large-video.mp4"; $localFileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "downloaded-video.mp4"; $file = $ctx->getWeb()->getFileByServerRelativeUrl($sourceFileUrl); $fh = fopen($localFileName, 'w+'); $file->download($fh)->executeQuery(); fclose($fh); echo "File downloaded to: $localFileName" . PHP_EOL; ``` -------------------------------- ### Authenticate SharePoint with User Credentials in PHP Source: https://github.com/vgrem/phpspo/blob/master/README.md This PHP code shows how to authenticate with SharePoint using user credentials (username and password). It utilizes the `UserCredentials` class and the `withCredentials` method of the `ClientContext` to establish a connection. ```php use Office365\Runtime\Auth\UserCredentials; use Office365\SharePoint\ClientContext; $credentials = new UserCredentials("{userName}", "{password}"); $ctx = (new ClientContext("{siteUrl}"))->withCredentials($credentials); ``` -------------------------------- ### Grant SharePoint Permissions with XML Source: https://github.com/vgrem/phpspo/wiki/How-to-connect-to-SharePoint-Online-and-and-SharePoint-2013-2016-2019-on-premises--with-app-principal This XML snippet defines the permission requests for a SharePoint app. It can be used to grant full control at the site collection level or tenant level, depending on the scope specified. ```xml ``` ```xml ``` -------------------------------- ### Create Microsoft Team (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Creates a new Microsoft Team using the Microsoft Graph API via the Office365 PHP SDK. This requires authentication credentials and the desired team name. The output includes the display name and ID of the newly created team. ```php acquireTokenForPassword($resource, $clientId, new UserCredentials("user@domain.com", "password")); } $client = new GraphServiceClient("acquireToken"); $teamName = "Project Phoenix Team"; $newTeam = $client->getTeams()->add($teamName)->executeQuery(); echo "Team created: " . $newTeam->getDisplayName() . PHP_EOL; echo "Team ID: " . $newTeam->getId() . PHP_EOL; ?> ``` -------------------------------- ### Upload File to SharePoint Source: https://context7.com/vgrem/phpspo/llms.txt Uploads files from a local directory to a specified SharePoint document library. It iterates through files in a local path and uploads them one by one. Requires the Office365 client library and appropriate credentials. ```php withCredentials($credentials); $localPath = "/path/to/local/files/"; $targetLibrary = "Documents"; $targetList = $ctx->getWeb()->getLists()->getByTitle($targetLibrary); foreach (glob($localPath . '*.*') as $filename) { $fileContent = file_get_contents($filename); $uploadedFile = $targetList->getRootFolder()->uploadFile(basename($filename), $fileContent); $ctx->executeQuery(); echo "Uploaded: " . $uploadedFile->getServerRelativeUrl() . PHP_EOL; } ``` -------------------------------- ### Create SharePoint Folder (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Creates a new folder within a specified SharePoint document library. This operation uses the Office365 PHP SDK and requires the parent folder's URL and the desired new folder name. It returns the server-relative URL and name of the newly created folder. ```php withCredentials($credentials); $folderName = "Archive_2025"; $rootFolder = $ctx->getWeb()->getFolderByServerRelativeUrl("Shared Documents"); $newFolder = $rootFolder->getFolders()->add($folderName)->executeQuery(); echo "Folder created: " . $newFolder->getServerRelativeUrl() . PHP_EOL; echo "Name: " . $newFolder->getName() . PHP_EOL; ?> ``` -------------------------------- ### Read SharePoint List Items (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md Demonstrates how to read list items from a SharePoint list. It shows two syntaxes: standard and fluent API. Requires the Office365 PHP SDK and valid SharePoint credentials. ```php use Office365\SharePoint\ClientContext; use Office365\Runtime\Auth\ClientCredential; use Office365\SharePoint\ListItem; $credentials = new ClientCredential("{client-id}", "{client-secret}"); $client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials); $web = $client->getWeb(); $list = $web->getLists()->getByTitle("{list-title}"); //init List resource $items = $list->getItems(); //prepare a query to retrieve from the $client->load($items); //save a query to retrieve list items from the server $client->executeQuery(); //submit query to SharePoint server /** @var ListItem $item */ foreach($items as $item) { print "Task: {$item->getProperty('Title')}\r\n"; } ``` ```php use Office365\SharePoint\ClientContext; use Office365\Runtime\Auth\ClientCredential; use Office365\SharePoint\ListItem; $credentials = new ClientCredential("{client-id}", "{client-secret}"); $client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials); $items = $client->getWeb() ->getLists() ->getByTitle("{list-title}") ->getItems() ->get() ->executeQuery(); /** @var ListItem $item */ foreach($items as $item) { print "Task: {$item->getProperty('Title')}\r\n"; } ``` -------------------------------- ### Authenticate SharePoint On-Premises with NTLM in PHP Source: https://github.com/vgrem/phpspo/blob/master/README.md This PHP snippet demonstrates NTLM authentication for SharePoint On-Premises environments. It uses `UserCredentials` with the username and password, and the `withNtlm` method of the `ClientContext` for connection. ```php use Office365\Runtime\Auth\UserCredentials; use Office365\SharePoint\ClientContext; $credentials = new UserCredentials("{userName}", "{password}"); $ctx = (new ClientContext("{siteUrl}"))->withNtlm($credentials); ``` -------------------------------- ### SharePoint Authentication using Client Credentials in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to SharePoint Online or On-Premises using application principal with client ID and secret. Requires the `office365-php-client` library. ```php withCredentials($credentials); // Verify connection $web = $ctx->getWeb()->get()->executeQuery(); echo "Connected to: " . $web->getTitle() . PHP_EOL; ?> ``` -------------------------------- ### SharePoint NTLM Authentication for On-Premises in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to SharePoint On-Premises using Windows NTLM authentication with username and password. Requires the `office365-php-client` library. ```php withNtlm($credentials); $web = $ctx->getWeb()->get()->executeQuery(); echo "Connected to on-premises: " . $web->getTitle() . PHP_EOL; ?> ``` -------------------------------- ### Microsoft Graph Authentication using User Credentials in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to Microsoft Graph with user credentials for delegated permissions. Requires the `office365-php-client` library. ```php getMe()->getDrive()->get()->executeQuery(); echo "Drive URL: " . $drive->getWebUrl() . PHP_EOL; ?> ``` -------------------------------- ### SharePoint Authentication using Certificate in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to SharePoint using an Azure AD app with a client certificate for enhanced security. Requires the `office365-php-client` library and the certificate file. ```php withClientCertificate($tenant, $clientId, $privateKey, $thumbprint); // Execute query $web = $ctx->getWeb()->get()->executeQuery(); echo "Authenticated with certificate" . PHP_EOL; ?> ``` -------------------------------- ### Check SharePoint File Existence (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Verifies if a file exists in SharePoint before proceeding with operations. It requires the Office365 PHP SDK and takes the file's server-relative URL as input. Outputs the file's name, size, and last modified date if it exists, or a 'not found' message. ```php withCredentials($credentials); $fileUrl = "/sites/{site}/Shared Documents/report.pdf"; try { $file = $ctx->getWeb()->getFileByServerRelativeUrl($fileUrl); $file->get()->executeQuery(); if ($file->exists()) { echo "File exists: " . $file->getName() . PHP_EOL; echo "Size: " . $file->getLength() . " bytes" . PHP_EOL; echo "Modified: " . $file->getTimeLastModified()->format('Y-m-d H:i:s') . PHP_EOL; } else { echo "File does not exist" . PHP_EOL; } } catch (Exception $e) { echo "Error checking file: " . $e->getMessage() . PHP_EOL; } ?> ``` -------------------------------- ### Create SharePoint List Item (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Adds a new item with specified properties to a SharePoint list. This operation requires a valid list title and an associative array of properties for the new item. The Office365-PHP-SDK and authentication are necessary. ```php withCredentials($credentials); $list = $ctx->getWeb()->getLists()->getByTitle("Tasks"); $itemProperties = [ 'Title' => 'Complete Project Documentation', 'Status' => 'Not Started', 'Priority' => 'High', 'DueDate' => '2025-12-31T00:00:00Z' ]; $item = $list->addItem($itemProperties)->executeQuery(); echo "Created item with ID: " . $item->getProperty('Id') . PHP_EOL; echo "Title: " . $item->getProperty('Title') . PHP_EOL; ``` -------------------------------- ### SharePoint Authentication using User Credentials in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to SharePoint Online using username and password. Requires the `office365-php-client` library. ```php withCredentials($credentials); $web = $ctx->getWeb()->get()->executeQuery(); echo "User authenticated: " . $web->getTitle() . PHP_EOL; ?> ``` -------------------------------- ### Upload File to OneDrive using PHP Source: https://context7.com/vgrem/phpspo/llms.txt Uploads a local file to OneDrive using the Office 365 Graph API. It requires the 'vendor/autoload.php' file, user credentials, and the local file path. The function returns details of the uploaded file, including its name, web URL, and size. ```php getMe() ->getDrive() ->getRoot() ->uploadFile($fileName, $fileContent) ->executeQuery(); echo "File uploaded: " . $uploadedFile->getName() . PHP_EOL; echo "Web URL: " . $uploadedFile->getWebUrl() . PHP_EOL; echo "Size: " . number_format($uploadedFile->getSize()) . " bytes" . PHP_EOL; ?> ``` -------------------------------- ### Microsoft Graph Authentication using Client Credentials in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Authenticates to the Microsoft Graph API using client secret for application permissions. Requires the `office365-php-client` library. ```php getMe()->get()->executeQuery(); echo "Connected to Graph API" . PHP_EOL; ?> ``` -------------------------------- ### List Files in SharePoint Folder (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves a list of all files contained within a specific SharePoint folder. This function utilizes the Office365 PHP SDK and takes the folder's server-relative URL as input. It outputs the name, size, and last modified date for each file found. ```php withCredentials($credentials); $folder = $ctx->getWeb()->getFolderByServerRelativeUrl("Shared Documents/Reports"); $files = $folder->getFiles()->get()->executeQuery(); /** @var File $file */ foreach ($files as $file) { echo "File: " . $file->getName() . PHP_EOL; echo "Size: " . number_format($file->getLength()) . " bytes" . PHP_EOL; echo "Modified: " . $file->getTimeLastModified()->format('Y-m-d H:i:s') . PHP_EOL; echo "---" . PHP_EOL; } ?> ``` -------------------------------- ### Read SharePoint List Items with Property Selection (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves all items from a specified SharePoint list and selects specific properties. This method is useful for fetching a subset of data to improve performance. It requires the Office365-PHP-SDK and credentials for authentication. ```php withCredentials($credentials); $list = $ctx->getWeb()->getLists()->getByTitle("Tasks"); $items = $list->getItems()->select(["Title", "Status", "DueDate"])->get()->executeQuery(); /** @var ListItem $item */ foreach ($items as $item) { echo "Task: " . $item->getProperty('Title') . PHP_EOL; echo "Status: " . $item->getProperty('Status') . PHP_EOL; } ``` -------------------------------- ### Upload Large File with Progress to SharePoint Source: https://context7.com/vgrem/phpspo/llms.txt Handles uploading large files (over 2MB) to SharePoint using a chunked upload mechanism. It includes a progress callback function to report the upload status. Requires the Office365 client library and client credentials. ```php withCredentials($credentials); $localPath = "/path/to/large-video.mp4"; $targetLibrary = "Documents"; $targetList = $ctx->getWeb()->getLists()->getByTitle($targetLibrary); $session = $targetList->getRootFolder()->getFiles()->createUploadSession( $localPath, "uploaded-video.mp4", function ($uploadedBytes) { echo "Progress: $uploadedBytes bytes uploaded" . PHP_EOL; } ); $ctx->executeQuery(); $targetFileUrl = $session->getFile()->getServerRelativeUrl(); echo "File uploaded successfully: $targetFileUrl" . PHP_EOL; } catch (Exception $e) { echo 'Upload failed: ' . $e->getMessage() . PHP_EOL; } ``` -------------------------------- ### Send Email with Attachments in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Sends an email message with file attachments using the Outlook Mail API. It requires the Office365 library and user credentials. The process involves creating the message, saving it, then adding the attachment and sending the complete message. ```php getMe()->getMessages()->createType(); $message->setSubject("Monthly Report with Attachments"); $message->setBody(new ItemBody(BodyType::Text, "Please find attached the monthly report.")); $message->setToRecipients([new EmailAddress(null, "recipient@domain.com")]); // Create message first $message = $client->getMe()->getMessages()->add($message)->executeQuery(); // Add attachments $filePath = "/path/to/report.pdf"; $attachment = new FileAttachment(); $attachment->setName("monthly-report.pdf"); $attachment->setContentBytes(base64_encode(file_get_contents($filePath))); $message->getAttachments()->add($attachment)->executeQuery(); // Send the message $message->send()->executeQuery(); echo "Email with attachment sent successfully" . PHP_EOL; ?> ``` -------------------------------- ### Query SharePoint List Items with OData Filter (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Fetches list items from a SharePoint list using an OData filter expression, sorting, and a top limit. This allows for targeted data retrieval. It depends on the Office365-PHP-SDK and valid authentication credentials. ```php withCredentials($credentials); $list = $ctx->getWeb()->getLists()->getByTitle("Documents"); $items = $list->getItems() ->select(["Title", "Modified", "FileLeafRef"]) ->filter("Title eq 'Important'") ->orderBy("Modified", false) ->top(10) ->get() ->executeQuery(); /** @var ListItem $item */ foreach ($items as $item) { echo $item->getProperty('Title') . " - " . $item->getProperty('Modified') . PHP_EOL; } ``` -------------------------------- ### Query SharePoint List Items with CAML (PHP) Source: https://context7.com/vgrem/phpspo/llms.txt Retrieves list items from SharePoint using a complex CAML query, including WHERE, OrderBy, and RowLimit clauses. This method is powerful for intricate data filtering and sorting. It requires the Office365-PHP-SDK and authentication details. ```php withCredentials($credentials); $camlXml = ' Active 100 '; $list = $ctx->getWeb()->getLists()->getByTitle("Tasks"); $query = new CamlQuery($camlXml); $items = $list->getItems($query)->executeQuery(); /** @var ListItem $item */ foreach ($items as $item) { echo $item->getProperty('Title') . " - Due: " . $item->getProperty('DueDate') . PHP_EOL; } ``` -------------------------------- ### Update SharePoint List Item (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md Demonstrates how to update an existing list item in a SharePoint list by its ID. Requires the Office365 PHP SDK, valid SharePoint credentials, and the item ID. Specific properties can be set before updating. ```php use Office365\SharePoint\ClientContext; use Office365\Runtime\Auth\ClientCredential; $credentials = new ClientCredential("{client-id}", "{client-secret}"); $client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials); $list = $client->getWeb()->getLists()->getByTitle("Tasks"); $listItem = $list->getItemById("{item-id-to-update}"); $listItem->setProperty('PercentComplete',1); $listItem->update()->executeQuery(); ``` -------------------------------- ### Send Email using Outlook Mail API in PHP Source: https://context7.com/vgrem/phpspo/llms.txt Sends an email message using the Outlook Mail API. Requires the Office365 library and authentication credentials. It constructs a message object with subject, body, recipients, and importance, then sends it. ```php acquireTokenForPassword($resource, "{client-id}", new UserCredentials("sender@domain.com", "password")); } $client = new GraphServiceClient("acquireToken"); /** @var Message $message */ $message = $client->getMe()->getMessages()->createType(); $message->setSubject("Q4 Budget Review"); $message->setBody(new ItemBody(BodyType::Html, "

Budget Report

Please review the attached Q4 budget.

")); $message->setToRecipients([ new EmailAddress(null, "manager@domain.com"), new EmailAddress(null, "finance@domain.com") ]); $message->setImportance("High"); $client->getMe()->sendEmail($message, false)->executeQuery(); echo "Email sent successfully" . PHP_EOL; ?> ``` -------------------------------- ### Send Email via Outlook Mail API (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md This snippet demonstrates how to send an email using the Outlook Mail REST API in PHP. It requires authentication and constructs a message object to be sent. ```php use Office365\GraphServiceClient; use Office365\Outlook\Message; use Office365\Outlook\ItemBody; use Office365\Outlook\BodyType; use Office365\Outlook\EmailAddress; use Office365\Runtime\Auth\AADTokenProvider; use Office365\Runtime\Auth\UserCredentials; function acquireToken() { $tenant = "{tenant}.onmicrosoft.com"; $resource = "https://graph.microsoft.com"; $provider = new AADTokenProvider($tenant); return $provider->acquireTokenForPassword($resource, "{clientId}", new UserCredentials("{UserName}", "{Password}")); } $client = new GraphServiceClient("acquireToken"); /** @var Message $message */ $message = $client->getMe()->getMessages()->createType(); $message->setSubject("Meet for lunch?"); $message->setBody(new ItemBody(BodyType::Text,"The new cafeteria is open.")); $message->setToRecipients([new EmailAddress(null,"fannyd@contoso.onmicrosoft.com")]); $client->getMe()->sendEmail($message,true)->executeQuery(); ``` -------------------------------- ### Delete SharePoint List Item (PHP) Source: https://github.com/vgrem/phpspo/blob/master/README.md Demonstrates how to delete a specific list item from a SharePoint list by its ID. Requires the Office365 PHP SDK, valid SharePoint credentials, and the item ID. ```php use Office365\SharePoint\ClientContext; use Office365\Runtime\Auth\ClientCredential; $credentials = new ClientCredential("{client-id}", "{client-secret}"); $client = (new ClientContext("https://{your-tenant-prefix}.sharepoint.com"))->withCredentials($credentials); $list = $client->getWeb()->getLists()->getByTitle("Tasks"); $listItem = $list->getItemById("{item-id-to-delete}"); $listItem->deleteObject()->executeQuery(); ```