### 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
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(); ```