### Search User by Name Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/users_samples.md This example demonstrates how to search for users, although the provided code snippet focuses on retrieving transitive members of a group and then fetching group details. The endpoint `/users/$search` is mentioned but not fully implemented in the example. ```APIDOC ## GET /users/$search ### Description Searches for users based on a query. The provided code snippet actually retrieves transitive members of a group for a given user and then fetches details of those groups. ### Method GET ### Endpoint /users/$search ### Query Parameters - **$search** (string) - Required - The search query string. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $userId = ""; try { $memberships = $graphServiceClient->users()->byUserId($userId)->transitiveMemberOf()->get()->wait(); if ($memberships && $memberships->getValue()) { foreach ($memberships->getValue() as $membership) { $obj = $graphServiceClient->directoryObjects()->byDirectoryObjectId($membership->getId())->get()->wait(); if ($obj && $obj->getOdataType() === '#microsoft.graph.group') { $group = $graphServiceClient->groups()->byGroupId($obj->getId())->get()->wait(); if ($group) { echo "Group ID: {$group->getId()}
"; echo "Group Types: " . json_encode($group->getGroupTypes()) . "
"; echo "Group Display Name: {$group->getDisplayName()}
"; echo "Group Mail: {$group->getMail()}

"; } } } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) Returns a collection of group objects that the user is a member of. #### Response Example ```json { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#groups", "value": [ { "id": "", "displayName": "Marketing", "groupTypes": ["Unified"], "mail": "marketing@contoso.onmicrosoft.com" } ] } ``` ``` -------------------------------- ### Basic Microsoft Graph API Call in PHP Source: https://github.com/microsoftgraph/msgraph-sdk-php/wiki/Getting-Started Demonstrates how to initialize the Graph client, set an access token, and make a GET request to retrieve user information. ```php use Microsoft\Graph\Graph; class UsageExample { $accessToken = 'xxx'; $graph = new Graph(); $graph->setAccessToken($accessToken); $user = $graph->createRequest("GET", "/me") ->setReturnType("User") ->execute(); echo "Hello, I am {$user->getGivenName()}."; } ``` -------------------------------- ### Get a Collection of Messages with Query Parameters Source: https://context7.com/microsoftgraph/msgraph-sdk-php/llms.txt Use a `RequestConfiguration` object to apply OData query options like `$select`, `$top`, `$skip`, and `$filter`, as well as custom headers, to collection requests. This example demonstrates fetching a subset of messages with specific fields. ```php 'outlook.body-content-type=text'] ); $messages = $graphServiceClient->me()->messages()->get($requestConfig)->wait(); foreach ($messages->getValue() as $message) { echo "Subject: {$message->getSubject()}\n"; echo "From: {$message->getFrom()->getEmailAddress()->getAddress()}\n"; } ``` -------------------------------- ### Get an Item in the Drive Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves a specific item within a drive. This example iterates through all items and prints their details. ```APIDOC ## GET AN ITEM IN THE DRIVE (GET /drives/{id}/items/{id}) ### Description Retrieves a specific item within a drive. This example iterates through all items and prints their details. ### Method GET ### Endpoint /drives/{id}/items/{itemId} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. - **itemId** (string) - Required - The unique identifier of the item. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $driveId = "DRIVE-ID"; $itemId = "ITEM-ID"; try { $item = $graphServiceClient->drives()->byDriveId($driveId)->items()->byDriveItemId($itemId)->get()->wait(); if ($item) { echo "Item ID: {$item->getId()}
"; echo "Item Name: {$item->getName()}
"; echo "Item Size: {$item->getSize()}
"; echo "Item Folder: " . json_encode($item->getFolder()) . "
"; echo "Item File: " . json_encode($item->getFile()) . "

"; } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the item. - **name** (string) - The name of the item. - **size** (integer) - The size of the item in bytes. - **folder** (object) - Information about the item if it is a folder. - **file** (object) - Information about the item if it is a file. #### Response Example ```json { "id": "item-id-1", "name": "Document.docx", "size": 20480, "file": {}, "folder": null } ``` ``` -------------------------------- ### Create Batch Request Content Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/general_samples.md Prepare a batch of requests to be sent together. This example adds three distinct operations to a BatchRequestContent object. ```php use Microsoft\Graph\Core\Requests\BatchRequestContent; use Microsoft\Graph\Generated\Models\Message; $message = new Message(); $message->setSubject("Test Subject"); $batchRequestContent = new BatchRequestContent([ $graphServiceClient->users()->byUserId(USER_ID)->messages()->byMessageId('id')->toDeleteRequestInformation(), $graphServiceClient->users()->byUserId(USER_ID)->messages()->toPostRequestInformation($message), $graphServiceClient->users()->byUserId(USER_ID)->toGetRequestInformation() ]); ``` -------------------------------- ### List All Items in a Drive Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves a list of items within a specific drive, with an option to filter items. This example filters for items whose names start with 'B'. ```APIDOC ## LIST ALL THE ITEMS IN A DRIVE (GET /drives/{id}/items) ### Description Retrieves a list of items within a specific drive, with an option to filter items. This example filters for items whose names start with 'B'. ### Method GET ### Endpoint /drives/{id}/items ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. #### Query Parameters - **filter** (string) - Optional - OData filter to apply to the query (e.g., "startswith(name, 'B')"). ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $driveId = "DRIVE-ID"; try { $requestConfig = new ItemsRequestBuilderGetRequestConfiguration(); $requestConfig->queryParameters = ItemsRequestBuilderGetRequestConfiguration::createQueryParameters(); $requestConfig->queryParameters->filter = "startswith(name, 'B')"; $items = $graphServiceClient->drives()->byDriveId($driveId)->items()->get($requestConfig)->wait(); if ($items && $items->getValue()) { foreach ($items->getValue() as $item) { echo "Item ID: {$item->getId()}
"; echo "Item Name: {$item->getName()}
"; echo "Item Size: {$item->getSize()}
"; echo "Item Folder: " . json_encode($item->getFolder()) . "
"; echo "Item File: " . json_encode($item->getFile()) . "

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) - **value** (array) - An array of item objects within the drive. - **id** (string) - The unique identifier for the item. - **name** (string) - The name of the item. - **size** (integer) - The size of the item in bytes. - **folder** (object) - Information about the item if it is a folder. - **file** (object) - Information about the item if it is a file. #### Response Example ```json { "value": [ { "id": "item-id-1", "name": "Budget.xlsx", "size": 10240, "file": {}, "folder": null } ] } ``` ``` -------------------------------- ### Get All Users in a Tenant Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/users_samples.md Retrieves a list of all users in the tenant. Ensure you have the necessary permissions to access user data. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); try { $users = $graphServiceClient->users()->get()->wait(); if ($users && $users->getValue()) { foreach ($users->getValue() as $user) { echo "User ID: {$user->getId()}
"; echo "User Display Name: {$user->getDisplayName()}
"; echo "User Mail: {$user->getMail()}

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` -------------------------------- ### Get All Users Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/users_samples.md Retrieves a list of all users in the tenant. It iterates through the users and prints their ID, display name, and email. ```APIDOC ## GET /users ### Description Retrieves a list of all users in the tenant. ### Method GET ### Endpoint /users ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); try { $users = $graphServiceClient->users()->get()->wait(); if ($users && $users->getValue()) { foreach ($users->getValue() as $user) { echo "User ID: {$user->getId()}
"; echo "User Display Name: {$user->getDisplayName()}
"; echo "User Mail: {$user->getMail()}

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) Returns a collection of user objects. #### Response Example ```json { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users", "value": [ { "id": "", "displayName": "Adele Vance", "mail": "AdeleV@contoso.onmicrosoft.com" }, { "id": "", "displayName": "Alex Wilber", "mail": "AlexW@contoso.onmicrosoft.com" } ] } ``` ``` -------------------------------- ### Get a Single Resource Source: https://context7.com/microsoftgraph/msgraph-sdk-php/llms.txt Retrieve a specific resource, such as a user, by its unique identifier using the fluent builder pattern. The `get()` method returns a Promise, which can be resolved using `.wait()` to obtain the resource object. ```APIDOC ## Get a Single Resource Retrieve a specific resource by ID using the fluent builder pattern. All operations return a Promise; call `.wait()` to block and get the result. ```php users()->byUserId('jane@contoso.com')->get()->wait(); echo "User Principal Name: {$user->getUserPrincipalName()}\n"; echo "Display Name: {$user->getDisplayName()}\n"; echo "User ID: {$user->getId()}\n"; } catch (ApiException $ex) { echo "Error {$ex->getResponseStatusCode()}: {$ex->getError()->getMessage()}\n"; } ``` ``` -------------------------------- ### Manage Drives and Drive Items with PHP SDK Source: https://context7.com/microsoftgraph/msgraph-sdk-php/llms.txt This snippet demonstrates how to list all drives, get the root folder of a specific drive, list its children, and filter items by name prefix. Replace 'DRIVE-ID' with the actual drive ID. ```php drives()->get()->wait(); foreach ($drives->getValue() as $drive) { echo "{$drive->getName()} ({$drive->getDriveType()}): {$drive->getWebUrl()}\n"; } // Get drive root folder $root = $graphServiceClient->drives()->byDriveId($driveId)->root()->get()->wait(); echo "Root child count: {$root->getFolder()->getChildCount()}\n"; // List root folder children $children = $graphServiceClient->drives()->byDriveId($driveId) ->items()->byDriveItemId('root')->children()->get()->wait(); foreach ($children->getValue() as $item) { echo "Name: {$item->getName()}, Size: {$item->getSize()} bytes\n"; } // Filter items by name prefix $requestConfig = new ItemsRequestBuilderGetRequestConfiguration( queryParameters: ItemsRequestBuilderGetRequestConfiguration::createQueryParameters( filter: "startswith(name, 'Report')" ) ); $filtered = $graphServiceClient->drives()->byDriveId($driveId)->items()->get($requestConfig)->wait(); foreach ($filtered->getValue() as $item) { echo "Filtered item: {$item->getName()}\n"; } ``` -------------------------------- ### Get Site Lists Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/sharepoint_samples.md Retrieves all lists within a specified SharePoint site. ```APIDOC ## Get Site Lists ### Description Retrieves all lists within a specified SharePoint site. ### Method GET ### Endpoint /sites/{site-id}/lists ### Parameters #### Path Parameters - **site-id** (string) - Required - The ID of the site. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $siteId = ""; $siteLists = $graphServiceClient->sites()->bySiteId($siteId)->lists()->get()->wait(); ``` ### Response #### Success Response (200) - **value** (array) - An array of list objects. - **id** (string) - The ID of the list. - **name** (string) - The name of the list. - **webUrl** (string) - The URL of the list. - **additionalData** (object) - Additional data associated with the list. #### Response Example ```json { "value": [ { "id": "", "name": "", "webUrl": "", "additionalData": {} } ] } ``` ``` -------------------------------- ### Create Batch Request with Dependencies Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/general_samples.md Construct a batch request where one operation depends on the completion of another. This example ensures a message is fetched before it's patched. ```php use Microsoft\Graph\Core\Requests\BatchRequestContent; use Microsoft\Graph\Core\Requests\BatchRequestItem; use Microsoft\Graph\Generated\Models\Message; $message = new Message(); $message->setSubject("Test Subject"); $request1 = new BatchRequestItem($graphServiceClient->users()->byUserId(USER_ID)->messages()->byMessageId('[id]')->toGetRequestInformation()); $request2 = new BatchRequestItem($graphServiceClient->users()->byUserId(USER_ID)->messages()->byMessageId('[id]')->toPatchRequestInformation($message)); $request2->dependsOn([$request1]); $batchRequestContent = new BatchRequestContent([ $request1, $request2 ]); ``` -------------------------------- ### v1.x vs v2.0 Authentication Token Retrieval Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/UPGRADING.md Compares how access tokens were retrieved and set in v1.x with the new Authentication Provider approach in v2.0. The v2.0 example shows initialization of the `GraphPhpLeagueAuthenticationProvider` with a `AuthorizationCodeContext` and scopes. ```php // v1.x $accessToken = getAccessToken(); // custom token retrieval method $graph = new Graph(); $graph->setAccessToken($accessToken); $graph->createRequest('GET', '/me') ->setAccessToken(getAccessToken()) //after initial token expires ... ``` ```php // v2.0 $tokenRequestContext = new AuthorizationCodeContext( 'tenantId', 'clientId', 'clientSecret', 'authCode', 'redirectUri' ); $scopes = ['User.Read', 'Mail.Read']; $authProvider = new GraphPhpLeagueAuthenticationProvider($tokenRequestContext, $scopes); ``` -------------------------------- ### Install Microsoft Graph SDK for PHP with Composer Source: https://github.com/microsoftgraph/msgraph-sdk-php/wiki/Getting-Started Add the Microsoft Graph SDK for PHP to your project's dependencies using Composer. ```json { "require": { "Microsoft/Graph": "^1.0" } } ``` -------------------------------- ### Get Collection of Items with Pagination Source: https://github.com/microsoftgraph/msgraph-sdk-php/wiki/Example-calls Retrieve a paginated collection of drive items, setting a page size and iterating through the results. ```php $docGrabber = $graph->createCollectionRequest("GET", "/me/drive/root/children") ->setReturnType(Model\DriveItem::class) ->setPageSize(2); $docs = $docGrabber->getPage(); foreach ($docs as $doc){ $docArray[] = $doc->getName(); } ``` -------------------------------- ### Get the raw HTTP response Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/general_samples.md This sample demonstrates how to use a custom response handler to retrieve the raw HTTP response from a request. ```APIDOC ## Use a Custom Response Handler / Get the raw HTTP response Define a response handler that implements the [Response Handler interface](https://github.com/microsoft/kiota-abstractions-php/blob/main/src/ResponseHandler.php) and pass it into the request using the request options. The SDK provides a default asynchronous response handler which returns a promise that resolves to a raw HTTP response. To get the raw response: ```php // PHP 7 $nativeResponseHandler = new NativeResponseHandler(); $config = new MeRequestBuilderGetRequestConfiguration(); $config->options = [new ResponseHandlerOption($nativeResponseHandler)]; $result = $graphServiceClient->me()->get($config)->wait(); $rawResponse = $result->getResponse(); // PHP 8 $nativeResponseHandler = new NativeResponseHandler(); $result = $graphServiceClient->me()->get(new MeRequestBuilderGetRequestConfiguration( options: [new ResponseHandlerOption($nativeResponseHandler)] ))->wait(); $rawResponse = $result->getResponse(); ``` ``` -------------------------------- ### Customize Middleware with Retry Options Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/general_samples.md Configure custom middleware options, such as retry policies, for requests. This example sets a retry option with 2 retries and a 5-second delay. ```php use Microsoft\Graph\Generated\Users\Item\Messages\MessagesRequestBuilderGetRequestConfiguration; use Microsoft\Kiota\Http\Middleware\Options\RetryOption; $requestConfig = new MessagesRequestBuilderGetRequestConfiguration(); $requestConfig->options = [new RetryOption(2, 5)]; $messages = $graphServiceClient->me()->messages()->get($requestConfig)->wait(); ``` -------------------------------- ### List Drive Items with Filter (PHP) Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves items within a specific drive, filtering by name starting with 'B'. Demonstrates configuring request options. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $driveId = "DRIVE-ID"; try { $requestConfig = new ItemsRequestBuilderGetRequestConfiguration(); $requestConfig->queryParameters = ItemsRequestBuilderGetRequestConfiguration::createQueryParameters(); $requestConfig->queryParameters->filter = "startswith(name, 'B')"; $items = $graphServiceClient->drives()->byDriveId($driveId)->items()->get($requestConfig)->wait(); if ($items && $items->getValue()) { foreach ($items->getValue() as $item) { echo "Item ID: {$item->getId()}
"; echo "Item Name: {$item->getName()}
"; echo "Item Size: {$item->getSize()}
"; echo "Item Folder: " . json_encode($item->getFolder()) . "
"; echo "Item File: " . json_encode($item->getFile()) . "

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` -------------------------------- ### Access SharePoint Sites and Lists with PHP SDK Source: https://context7.com/microsoftgraph/msgraph-sdk-php/llms.txt This code allows you to retrieve site metadata, list all document libraries (lists) within a site, and get items from a specific list. Replace 'your-site-id' and 'your-list-id' with actual IDs. ```php sites()->bySiteId($siteId)->get()->wait(); echo "Site: {$site->getName()}, URL: {$site->getWebUrl()}\n"; // List all document libraries / lists in the site $lists = $graphServiceClient->sites()->bySiteId($siteId)->lists()->get()->wait(); foreach ($lists->getValue() as $list) { echo "List: {$list->getName()} (ID: {$list->getId()})\n"; } // Get items in a specific list $items = $graphServiceClient->sites()->bySiteId($siteId) ->lists()->byListId($listId)->items()->get()->wait(); foreach ($items->getValue() as $item) { echo "Item ID: {$item->getId()}, URL: {$item->getWebUrl()}\n"; echo "Additional data: " . json_encode($item->getAdditionalData()) . "\n"; } ``` -------------------------------- ### Get First Page of Drive Items with Page Size Source: https://github.com/microsoftgraph/msgraph-sdk-php/wiki/Paging-through-Collections Use `createCollectionRequest` to set the HTTP method, endpoint, return type, and page size. Call `getPage()` to retrieve the first page of results. ```php $docGrabber = $graph->createCollectionRequest("GET", "/me/drive/root/children") ->setReturnType(Model\DriveItem::class) ->setPageSize(2); $docs = $docGrabber->getPage(); foreach ($docs as $doc){ $docArray[] = $doc->getName(); } ``` -------------------------------- ### Get SharePoint Site List Items using PHP Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/sharepoint_samples.md Retrieves all items within a specified SharePoint list. This sample iterates through the items and displays their details. Requires both site ID and list ID. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $siteId = ""; $listId = ""; $graphServiceClient = new GraphServiceClient($tokenRequestContext); try { $siteListItems = $graphServiceClient->sites()->bySiteId($siteId)->lists()->byListId($listId)->items()->get()->wait(); foreach ($siteListItems->getValue() as $item) { echo "Site ID: {$item->getId()}\n"; echo "Site Name: {$item->getName()}\n"; echo "Site Additional Data: " . json_encode($item->getAdditionalData()) . "\n"; echo "Site URL: {$item->getWebUrl()}\n"; } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; ``` -------------------------------- ### Get a Group Drive Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/groups_samples.md This snippet demonstrates how to retrieve a specific drive belonging to a group using the Microsoft Graph SDK for PHP. It shows how to instantiate the client, specify the group and drive IDs, make the API call, and process the response, including error handling. ```APIDOC ## GET /groups/{id}/drives/{id} ### Description Retrieves a specific drive associated with a group. ### Method GET ### Endpoint /groups/{id}/drives/{id} ### Parameters #### Path Parameters - **groupId** (string) - Required - The ID of the group. - **driveId** (string) - Required - The ID of the drive to retrieve. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $groupId = ""; $driveId = ""; try { $drive = $graphServiceClient->groups()->byGroupId($groupId)->drives()->byDriveId($driveId)->get()->wait(); if ($drive) { echo "Drive ID: " . $drive->getId() . "
"; echo "Drive Type: " . $drive->getDriveType() . "
"; echo "Drive Name: " . $drive->getName() . "
"; echo "Drive Web URL: " . $drive->getWebUrl() . "
"; echo "Drive Items: " . json_encode($drive->getItems()) . "

"; } } catch (ApiException $ex) { echo $ex->getError()->getMessage(); } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the drive. - **driveType** (string) - The type of the drive (e.g., 'documentLibrary'). - **name** (string) - The name of the drive. - **webUrl** (string) - The URL to access the drive in a web browser. - **items** (array) - A collection of items within the drive. #### Response Example ```json { "id": "", "driveType": "documentLibrary", "name": "Documents", "webUrl": "https://contoso-my.sharepoint.com/personal/user_contoso_com/Documents", "items": [ // ... array of drive items ] } ``` ``` -------------------------------- ### Create AuthorizationCodeContext for User Access Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/README.md Use AuthorizationCodeContext to get access on behalf of a user. This requires handling user redirection to the Microsoft Identity login page to obtain an authorization code. Ensure you have the correct tenant ID, client ID, client secret, authorization code, and redirect URI. ```php setBaseUrl('https://graph.microsoft.com/') ->setApiVersion('v1.0') ->setAccessToken('xyz'); ``` ```php // 2.0 $tokenRequestContext = new ClientCredentialContext( 'tenantId', 'clientId', 'clientSecret' ); // uses https://graph.microsoft.com/.default scopes $graphServiceClient = new GraphServiceClient($tokenRequestContext); ``` -------------------------------- ### Create Graph Client with Client Credentials Context Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/authentication_samples.md Initialize a GraphServiceClient for requests without a signed-in user, using application permissions. Uses default scopes if none are specified. ```php use Microsoft\Graph\GraphServiceClient; use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext; // Uses https://graph.microsoft.com/.default scopes if none are specified $tokenRequestContext = new ClientCredentialContext( 'tenantId', 'clientId', 'clientSecret' ); $graphServiceClient = new GraphServiceClient($tokenRequestContext); ``` -------------------------------- ### List all applications in a tenant Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/application_samples.md Retrieves and displays a list of all applications registered in the tenant. Ensure you have authenticated and obtained a valid access token before making this call. ```php applications()->get()->wait(); if ($applications && $applications->getValue()) { foreach ($applications->getValue() as $app) { echo "Application ID: {$app->getId()}
"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ?> ``` -------------------------------- ### Create Graph Client with Custom National Cloud Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/authentication_samples.md Initialize a GraphServiceClient for a custom National Cloud deployment, such as Microsoft Cloud for China. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes, NationalCloud::CHINA); ``` -------------------------------- ### Get a Single User Resource by ID Source: https://context7.com/microsoftgraph/msgraph-sdk-php/llms.txt Retrieve a specific user resource by their principal name or object ID using the fluent builder pattern. All operations return a Promise; call `.wait()` to block and get the result. Handle potential API exceptions. ```php users()->byUserId('jane@contoso.com')->get()->wait(); echo "User Principal Name: {$user->getUserPrincipalName()}\n"; echo "Display Name: {$user->getDisplayName()}\n"; echo "User ID: {$user->getId()}\n"; } catch (ApiException $ex) { echo "Error {$ex->getResponseStatusCode()}: {$ex->getError()->getMessage()}\n"; } ``` -------------------------------- ### Implement and use a custom AccessTokenCache Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/authentication_samples.md Demonstrates how to set a cache key on `TokenRequestContext` and initialize a custom `AccessTokenCache` implementation. This is for advanced scenarios where specific cache key management is required. ```php $accessToken = new AccessToken([ 'access_token' => $accessToken, 'refresh_token' => $refreshToken, 'expires' => ... ]); $tokenRequestContext->setCacheKey($accessToken); // init custom cache with tokens mapped to specific user/app using $tokenRequestContext->getCacheKey() $customCache = new CustomCache($tokenRequestContext->getCacheKey(), $accessToken); // init graph client $graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( GraphPhpLeagueAccessTokenProvider::createWithCache( $customCache, $tokenRequestContext, $scopes ) ) ); ``` -------------------------------- ### Get Site List Items Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/sharepoint_samples.md Retrieves all items within a specific list in a SharePoint site. ```APIDOC ## Get site list items ### Description Retrieves all items within a specific list in a SharePoint site. ### Method GET ### Endpoint /sites/{site-id}/lists/{list-id}/items ### Parameters #### Path Parameters - **site-id** (string) - Required - The ID of the site. - **list-id** (string) - Required - The ID of the list. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $siteId = ""; $listId = ""; $siteListItems = $graphServiceClient->sites()->bySiteId($siteId)->lists()->byListId($listId)->items()->get()->wait(); ``` ### Response #### Success Response (200) - **value** (array) - An array of list item objects. - **id** (string) - The ID of the list item. - **name** (string) - The name of the list item. - **webUrl** (string) - The URL of the list item. - **additionalData** (object) - Additional data associated with the list item. #### Response Example ```json { "value": [ { "id": "", "name": "", "webUrl": "", "additionalData": {} } ] } ``` ``` -------------------------------- ### Get Site By Site ID Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/sharepoint_samples.md Retrieves details of a specific SharePoint site using its ID. ```APIDOC ## Get Site By Site ID ### Description Retrieves details of a specific SharePoint site using its ID. ### Method GET ### Endpoint /sites/{site-id} ### Parameters #### Path Parameters - **site-id** (string) - Required - The ID of the site to retrieve. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $siteId = ""; $siteData = $graphServiceClient->sites()->bySiteId($siteId)->get()->wait(); ``` ### Response #### Success Response (200) - **id** (string) - The ID of the site. - **name** (string) - The name of the site. - **webUrl** (string) - The URL of the site. #### Response Example ```json { "id": "", "name": "", "webUrl": "" } ``` ``` -------------------------------- ### Create Graph Client with Authorization Code Context Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/authentication_samples.md Initialize a GraphServiceClient for requests with a signed-in user using an AuthorizationCodeContext. Requires the tenant ID, client ID, client secret, authorization code, and redirect URI. ```php use Microsoft\Graph\GraphServiceClient; use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext; $tokenRequestContext = new AuthorizationCodeContext( 'tenantId', 'clientId', 'clientSecret', 'authCode', 'redirectUri' ); $scopes = ['User.Read', 'Mail.ReadWrite']; $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); ``` -------------------------------- ### Download an item Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/general_samples.md This sample shows how to download the content of an item, such as a file, using the Microsoft Graph SDK for PHP. ```APIDOC ## Download an item ```php use Microsoft\Graph\GraphServiceClient; use Microsoft\Kiota\Abstractions\ApiException; use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext; $tokenRequestContext = new AuthorizationCodeContext( 'tenantId', 'clientId', 'clientSecret', 'authCode', 'redirectUri' ); $scopes = ['Files.ReadWrite']; $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); try { $fileContents = $graphServiceclient->drives()->byDriveId('driveId')->items()->byDriveItemId('itemId')->content()->get()->wait(); } catch (ApiException $ex) { echo $ex->getError()->getMessage(); } ``` ``` -------------------------------- ### Get the Root Folder of the Drive Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves the root folder of a specific drive. It then prints details about the root folder. ```APIDOC ## GET THE ROOT FOLDER OF THE DRIVE (GET /drives/{id}/root) ### Description Retrieves the root folder of a specific drive. It then prints details about the root folder. ### Method GET ### Endpoint /drives/{id}/root ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $driveId = "DRIVE-ID"; // Replace with the actual drive ID try { $root = $graphServiceClient->drives()->byDriveId($driveId)->root()->get()->wait(); if ($root) { echo "Root ID: {$root->getId()}
"; echo "Root Name: {$root->getName()}
"; echo "Folder Child Count: " . ($root->getFolder() ? $root->getFolder()->getChildCount() : 'N/A') . "
"; echo "Root: " . json_encode($root->getRoot()) . "
"; echo "Root Size: {$root->getSize()}
"; } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the root folder. - **name** (string) - The name of the root folder (usually 'root'). - **folder** (object) - Information about the folder, including child count. - **childCount** (integer) - The number of direct children in the folder. - **root** (object) - Indicates if this is the root folder. - **size** (integer) - The total size of the folder's contents in bytes. #### Response Example ```json { "id": "root", "name": "root", "folder": { "childCount": 50 }, "root": {}, "size": 10485760 } ``` ``` -------------------------------- ### Get Drive by ID Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves a specific drive using its unique ID. It then prints the details of the retrieved drive. ```APIDOC ## GET DRIVE BY ID (GET /drives/{id}) ### Description Retrieves a specific drive using its unique ID. It then prints the details of the retrieved drive. ### Method GET ### Endpoint /drives/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```php $driveId = "DRIVE-ID"; try { $drive = $graphServiceClient->drives()->byDriveId($driveId)->get()->wait(); if ($drive) { echo "Drive ID: {$drive->getId()}
"; echo "Drive Type: {$drive->getDriveType()}
"; echo "Drive Name: {$drive->getName()}
"; echo "Drive Description: {$drive->getDescription()}
"; echo "Drive Web URL: {$drive->getWebUrl()}
"; } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the drive. - **driveType** (string) - The type of the drive (e.g., 'personal', 'business'). - **name** (string) - The name of the drive. - **description** (string) - A description of the drive. - **webUrl** (string) - The URL to access the drive in a web browser. #### Response Example ```json { "id": "drive-id-1", "driveType": "personal", "name": "My Documents", "description": "User's personal documents", "webUrl": "https://onedrive.live.com/" } ``` ``` -------------------------------- ### List All Groups in Tenant Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/groups_samples.md Retrieves a list of all groups in the tenant. Requires the GraphServiceClient to be initialized with authentication context. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); try { $groups = $graphServiceClient->groups()->get()->wait(); if ($groups && $groups->getValue()) { foreach ($groups->getValue() as $group) { echo "Group ID: {$group->getId()}
"; echo "Group Display Name: {$group->getDisplayName()}

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` -------------------------------- ### Initialize GraphServiceClient with Specific Scopes Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/README.md Initialize the GraphServiceClient with a token request context and a specific array of scopes for fine-grained access control. ```php // With specific scopes $scopes = ['User.Read', 'Mail.ReadWrite']; $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); ``` -------------------------------- ### List All Groups in the Tenant Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/groups_samples.md Retrieves a list of all groups within the tenant. This operation is useful for getting an overview of all available groups. ```APIDOC ## LIST ALL GROUPS IN THE TENANT (GET /groups) ### Description Retrieves a list of all groups within the tenant. ### Method GET ### Endpoint /groups ### Parameters None ### Request Example ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $groups = $graphServiceClient->groups()->get()->wait(); ``` ### Response #### Success Response (200) - **value** (array) - An array of group objects. - **id** (string) - The unique identifier for the group. - **displayName** (string) - The display name of the group. ### Response Example ```json { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#groups", "value": [ { "id": "", "displayName": "Group One" }, { "id": "", "displayName": "Group Two" } ] } ``` ``` -------------------------------- ### Get Drive Items (PHP) Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/drives_samples.md Retrieves all items within a specified drive. Includes error handling for API exceptions. ```php $graphServiceClient = new GraphServiceClient($tokenRequestContext); $driveId = "DRIVE-ID"; try { $items = $graphServiceClient->drives()->byDriveId($driveId)->items()->get()->wait(); if ($items && $items->getValue()) { foreach ($items->getValue() as $item) { echo "Item ID: {$item->getId()}
"; echo "Item Name: {$item->getName()}
"; echo "Item Size: {$item->getSize()}
"; echo "Item Folder: " . json_encode($item->getFolder()) . "
"; echo "Item File: " . json_encode($item->getFile()) . "

"; } } } catch (ApiException $ex) { echo "Error: " . $ex->getResponseStatusCode() . "\n"; echo "Error: " .$ex->getError()->getMessage();"; } ``` -------------------------------- ### Initialize InMemoryAccessTokenCache with multiple tokens Source: https://github.com/microsoftgraph/msgraph-sdk-php/blob/main/docs/authentication_samples.md Initialize the `InMemoryAccessTokenCache` and add multiple `TokenRequestContext`-`AccessToken` pairs using the `withToken` method. This allows managing tokens for multiple users or application contexts within the same cache. ```php use Microsoft\Kiota\Authentication\Cache\InMemoryAccessTokenCache; use Microsoft\Graph\GraphServiceClient; use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAccessTokenProvider; use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider; use League\OAuth2\Client\Token\AccessToken; $tokenRequestContext = new AuthorizationCodeContext( 'tenantId', 'clientId', 'clientSecret', 'authCode', // use a placeholder value since user is not signed in again 'redirectUri' ); $cache = (new InMemoryAccessTokenCache($tokenRequestContext, new AccessToken([ // ... ]))); $cache->withToken($tokenRequestContext2, new AccessToken([ // ... ]))->withToken($tokenRequestContext, new AccessToken([ // ... ]))->withToken($tokenRequestContext3, new AccessToken()); $graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( GraphPhpLeagueAccessTokenProvider::createWithCache( $cache, $tokenRequestContext, $scopes ) ) ); ```