CURL PHP send image

2020-01-24 10:01发布

It's trivial to get image from server but I think about something different. It is crazy question but... Is it possible to send file (image) to a server but not using form upload or ftp connection? I want to send a request to eg. http://www.example.com/file.php with binary content. I think I need to set Content-type header image/jpeg but how to add some content to my request?

标签: php curl
4条回答
走好不送
2楼-- · 2020-01-24 10:13

The only code worked for me with PHP 7.0

$file = new \CURLFile('@/path/to/image.jpeg'); //<-- Path could be relative
$data = array('name' => 'Foo', 'file' => $file);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
//CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0
//So next line is required as of php >= 5.6.0
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

Thanks to @AndyLin for his answer and this source.

查看更多
爷、活的狠高调
3楼-- · 2020-01-24 10:20

there are multiple ways to use curl to upload image files, e.g.:

$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/path/to/image.jpeg');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
//CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0
//So next line is required as of php >= 5.6.0
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

you can check the examples at: http://au.php.net/manual/en/function.curl-setopt.php

查看更多
够拽才男人
4楼-- · 2020-01-24 10:20

see http://docs.php.net/function.curl-setopt:

CURLOPT_POSTFIELDS The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
查看更多
劳资没心,怎么记你
5楼-- · 2020-01-24 10:26

VolkerK is completely right but my experience suggest that sending a file "@" operator will only work with arrays.

$post['file'] = "@FILE_Path"

Now you can send the file using CURLOPT_POSTFIELDS

查看更多
登录 后发表回答