Dherya Dherya - 2 months ago 12
PHP Question

file post/upload through curl in php

This is my curl initiation code:

$target="url/curlUploadHandler.php";
$args = new CURLFile('down.png', 'image/png','test'); //file to post
$postFields = array('file' => $args);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_SAFE_UPLOAD, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
$r = curl_exec($curl);
curl_close($curl);
print_r($r); // to get response from the page


And this is to check whether given file is getting posted or not:

curlUploadHandler.php

if($_REQUEST){
var_dump($_REQUEST);
}


or

if( $_FILES ) {
var_dump($_FILES );}


I am testing this code on local. Posting fields like string or integer is working fine but posting an image or any other file is not giving me any output. Am I missing some options in
cURL
or doing something wrong? I have checked the docs already php docs. Help me out please.

And please comment before downvoting :/ if you have to :(

Answer

$target must be "http://[HOST]/url/curlUploadHandler.php"

Check for errors

if( $errno = curl_errno($curl) ) { 
    $error_message = curl_strerror($errno); 
    echo "cURL error ({$errno}):\n {$error_message}"; 
}   

and

  • put in your code echo getcwd(); to check the full path
  • check with is_readable the image
  • check permisions of image