Muhammed Hafil Muhammed Hafil - 6 months ago 48
PHP Question

Upload files using curl to remote api

I am trying to upload the files users uploaded along with other post data to remote api using curl. This what i have done so far

$_POST['certf'] = '@'.$_FILES['certf']['tmp_name'].';filename=' . $_FILES['certf']['name'];

$url = "example.com/app_handler.php?key=key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
$result = curl_exec($ch);
curl_close($ch);
echo $result;


In the receiving side i have just printed the $_FILES but it is empty. all the tutorials i have found on internet saying that can accessed $_FILES and we can use it as normal file upload from there. What did i miss here?

Answer Source

Try to send file with CurlFile

$filePath= $_FILES['file1']['tmp_name'];
$fileType= $_FILES['file1']['type'];
$fileName= $_FILES['file1']['name'];
$post_data['certf'] = new \CurlFile($filePath, $fileType, $fileName);

$url = "example.com/app_handler.php?key=key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download