PHP cURL creates empty file name only (0 bytes) - not transferring actual file

925 views Asked by At

I'm using a File Type input to pass FormData ($_FILES['files']) to PHP via Ajax

My PHP cURL looks like this:

$headers = array(
    "Authorization: Bearer " . <token>, 
    "Host: graph.microsoft.com",
    "Content-Type: multipart/form-data",
    "Content-Length: 0",
);

$filename = $_FILES['file']['name'];

$postfile = curl_init('https://graph.microsoft.com/v1.0/users/' . <userid> . '/drive/root:/<folder>/' . $filename . ':/content'); 
curl_setopt($postfile, CURLOPT_PUT, 1);
curl_setopt($postfile,CURLOPT_HEADER,false);
curl_setopt($postfile, CURLOPT_HTTPHEADER, $headers);
curl_setopt($postfile,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($postfile,CURLOPT_SSL_VERIFYHOST,0);

$result = curl_exec($postfile);
curl_close($postfile); 

This creates a file in the correct folder of the user's OneDrive with the correct extension and everything, but they are all empty (0 bytes).

I've tested this with many files of different types for hours, and it's always the same.

Where am I going wrong?

2

There are 2 answers

3
LuRy On

You have mising filedata Try add following to your curl

$fh_res = fopen($_FILES['file']['tmp_name'], 'r');

curl_setopt($postfile, CURLOPT_INFILE, $fh_res);
curl_setopt($postfile, CURLOPT_INFILESIZE, filesize($_FILES['file']['tmp_name']));
0
Sofistikat On

I finally solved it with the following:

    $filename = $_FILES['file']['name'];
    $filecon = fopen($_FILES['file']['tmp_name'],'r');
    $filesize = filesize($_FILES['file']['tmp_name']);

    $headers = array(
        "Authorization: Bearer " . <token>, 
        "Host: graph.microsoft.com",
        "Content-Type: application/json",
        "Content-Length: " . $filesize,
    );

    $postfile = curl_init('https://graph.microsoft.com/v1.0/users/' . <userid> . '/drive/root:/<folder>/' . $filename . ':/content'); 
    
    curl_setopt($postfile, CURLOPT_PUT, 1);
    curl_setopt($postfile,CURLOPT_HEADER,0);
    curl_setopt($postfile, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($postfile, CURLOPT_UPLOAD, 1);
    curl_setopt($postfile, CURLOPT_INFILE, $filecon);
    curl_setopt($postfile, CURLOPT_INFILESIZE, $filesize);

    $result = curl_exec($postfile);
    curl_close($postfile); 

Hope this helps anyone looking for PHP cURL upload to OneDrive!