Search code examples
phpapicurlonedrive

How Upload large files to Onedrive using PHP-Curl


I need to upload file size grater than 4MB to onedrive account. I am trying with PHP and curl for this. Is anyone tried for this option, Please help me out to solve this issue.


Solution

  • $url='https://graph.microsoft.com/v1.0/me/drive/root:/filename:/createUploadSession';

        $data= '{}';
        $header = array('Content-Type: json',
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "Authorization: bearer {Access Token}");
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    

    get the uploadURL from the result,

        $graph_url = $result['uploadUrl'];
        $fragSize = 320 * 1024;
        $file = file_get_contents($filename_location);
        $fileSize = strlen($file);
        $numFragments = ceil($fileSize / $fragSize);
        $bytesRemaining = $fileSize;
        $i = 0;
        $ch = curl_init($graph_url);
        while ($i < $numFragments) {
            $chunkSize = $numBytes = $fragSize;
            $start = $i * $fragSize;
            $end = $i * $fragSize + $chunkSize - 1;
            $offset = $i * $fragSize;
            if ($bytesRemaining < $chunkSize) {
                $chunkSize = $numBytes = $bytesRemaining;
                $end = $fileSize - 1;
            }
            if ($stream = fopen($filename_location, 'r')) {
                // get contents using offset
                $data = stream_get_contents($stream, $chunkSize, $offset);
                fclose($stream);
            }
    
            $content_range = " bytes " . $start . "-" . $end . "/" . $fileSize;
            $headers = array(
                "Content-Length: $numBytes",
                "Content-Range:$content_range"
            );
            curl_setopt($ch, CURLOPT_URL, $graph_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, constant('CURL_SSL_VERIFYPEER_STATUS'));
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $server_output = curl_exec($ch);
            $info = curl_getinfo($ch);
    
            $bytesRemaining = $bytesRemaining - $chunkSize;
            $i++;
        }
    

    And when you passing the last set of data it should be the correct data bytes. Otherwise it will fail the upload session.