0

I am using cURL for the first time. I have to send one image file and one audio file posted by the user.

My cURL code is working, but instead of an image file and an audio file my code is sending a .tmp file.

I googled it, but in every example I found they have used realpath of file directly.

I tried to find real path of the file, but I didn't find any solution. Here is my code block in which I am collecting all data in an array to pass it to cURL:

$name = $_POST['name'];

$image = $_POST['image']['name'];
$imagetmp = $_POST['image']['tmp_name'];
$imagesize = $_POST['image']['size'];
$imagepath = '@'.$imagetmp;

$audio = $_POST['audio']['name'];
$audiotmp = $_POST['audio']['tmp_name'];
$audiosize = $_POST['audio']['size'];
$audiopath = '@'.$audiotmp;

$data = array("name" => $name, "image"=> $imagepath, "audio" => $audiopath); //array to sned data using cURL

//my cURL code to post data

Where am I doing wrong? How to send files using cURL?

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
Prachi Sharma
  • 239
  • 1
  • 4
  • 13

2 Answers2

0

This is what I used to post file data:

$filedata = file_get_contents('file_location/filename.jpg');    
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/octet-stream'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($ch);
curl_close($ch);
Schalk Keun
  • 538
  • 4
  • 13
-2

You can use file=@path with curl

curl -kiSs -X POST https://<domain>/path/to/api/files/ \
-F "param1=param2" \
-F "file=@/path/to/test.xlsx"  \
-H "Authorization":"bearer eyJhbGciOiJIUzI1NiIsIn"

File successfully uploaded (test.xlsx!) 

  • The `@` syntax was deprecated in PHP 5.6. In currently supported versions of PHP, you need to use the CurlFile class. https://www.php.net/manual/en/class.curlfile.php – ceejayoz Nov 25 '20 at 03:10