esafwan esafwan - 5 months ago 17
PHP Question

Invalid file type returned when posting via PHP Curl

I am posting an image to an API using CURL. It works perfectly. But when I do the same with php there is some issue that am not able to resolve. I tried setting

CURLOPT_SAFE_UPLOAD
to
TRUE
in php.ini file.

The API can accept access token both as URL parameter and in header.

curl -v -F 'image=@/var/www/devel/id-card-concept.jpg;type=image/jpeg' -F 'title=test upload' -F 'description=test upload description' -H "Authorization: Bearer Access-Token" "https://api.site.com/v1/uploads"


Below is my Php Code:

$filename = 'id-card-concept.jpg';
$target_url = "https://api.site.com/v1/uploads?access_token=Access-Token";
$file_name_with_full_path = realpath('id-card-concept.jpg');
$post = array('title' => 'Via Api','image'=>'@'.$filename);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;


I get the following error:

Array ( ) { "message": "Validation failed.", "errors": [ { "attribute": "image", "message": "is an invalid file type" } ] }


As per my understanding the image is failing validation.

Answer

Try change:

$post = array('title' => 'Via Api','image'=>'@'.$filename);

To:

$post = array('title' => 'Via Api','image'=>'@/var/www/devel/'.$filename.';type=image/jpeg');

Or to:

$post = array('title' => 'Via Api','image'=>'@'.$file_name_with_full_path.$filename.';type=image/jpeg');

See full correct code:

$filename = 'id-card-concept.jpg';
$post = array('title' => 'Via Api','file'=>'@/var/www/devel/'.$filename.';type=image/jpeg');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.site.com/v1/uploads?access_token=cfbf79449f6b71212b3983a49be0056dcb6cd0838c6904bdb9a8f461f9e04220");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

See more on function.curl-setopt.

Comments