I am having this problem from last few days to develop a CURL request in php to post file data to an API.
Here is the CURL request
$ curl --request POST \
--url 'UPLOAD_URL' \
--upload-file 'PATH_TO_FILE' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
for PATH_TO_FILE I have tried each and every method published over the web and stackoverflow too.
here is my PHP code
<?php
header('Content-Type: application/json');
$sheader = array('Authorization: Bearer '.$_SESSION['access_token']);
$filename = $_FILES['upload-file']['name'];
$filedata = $_FILES['upload-file']['tmp_name'];
$filesize = $_FILES['upload-file']['size'];
$filetype = $_FILES['upload-file']['type'];
if($filename != '')
{
$ch = curl_init();
$cFile = new CURLFile(realpath($filename), $filetype, 'harish.jpg');
//$cFile = '@'. realpath($filename);
$data = array('upload-file' => $cFile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $cFile);
//curl_setopt($ch, CURLOPT_POSTFIELDS, realpath($filename));
curl_setopt($ch, CURLOPT_URL, $_POST['upload_url']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $sheader);
curl_exec($ch);
echo json_encode($ch);
//echo json_encode(array('filename'=>$filename, 'temp_path'=>$filedata, 'basepath'=>realpath($filename)));
} else {
echo 'There is no file selected';
}
Mostly the solution i have found on the web are these two mentioned below
Method 1 (for php < 5.5)
'@'.$filepath
Method 2 (for php > 5.5)
CURLFile($filename, $filetype, 'somefile.jpg');
or
curl_file_create($filedata, 'image/jpeg', $filename);
None of the above worked for me. I have use realpath($filename) too inside CURLFile to fetch absolute path of the file, but sadly that also not worked.