Search code examples
phpcurloffice365onedrive

Upload file to Office 365 Onedrive Business account using PHP-Curl


I'm trying to upload a JSON file to a new folder in OneDrive Business AC account using cURL. While uploading, I am getting the following error:

HTTP status code not expected - got - 401

Here is my code:

$uri = "https://graph.microsoft.com/v1.0/me/drive/root/new/sample.json/content?access_token=accesstoken";

function curl_put($uri, $fp) {
    $output = "";

    try {
        $pointer = fopen($fp, 'r+');

        $stat = fstat($pointer);
        $pointersize = $stat['size'];
        $ch = curl_init($uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_PUT, true);
        curl_setopt($ch, CURLOPT_INFILE, $pointer);
        curl_setopt($ch, CURLOPT_INFILESIZE, (int) $pointersize);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    }
}

Solution

  • https://graph.microsoft.com/v1.0/me/drive/root:/foldername/filename:/content

    Pass the header as :

    $headers = array( 'Content-Type: application/text', "Cache-Control: no-cache", "Pragma: no-cache", "Authorization: bearer ".$token );

    and pass the data from the file using file_get_contents.