CURL PHP发送图像

时间:2010-08-08 08:02:10

标签: php curl

从服务器获取图像是微不足道的,但我想到了不同的东西。这是一个疯狂的问题,但是...是否可以将文件(图像)发送到服务器但不使用表单上传或ftp连接?我想向例如发送请求。 http://www.example.com/file.php包含二进制内容。我想我需要设置Content-type header image / jpeg但是如何在我的请求中添加一些内容?

6 个答案:

答案 0 :(得分:20)

有多种方法可以使用curl上传图像文件,例如:

$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);

您可以查看以下示例:http://au.php.net/manual/en/function.curl-setopt.php

答案 1 :(得分:10)

请参阅http://docs.php.net/function.curl-setopt

CURLOPT_POSTFIELDS 在HTTP“POST”操作中发布的完整数据。 要发布文件,请在文件前加上@并使用完整路径。这可以作为urlencoded字符串传递,如'para1 =val1¶2= val2& ...',或者作为一个数组,字段名称作为键,字段数据作为值。如果value是数组,则Content-Type标头将设置为multipart / form-data。

答案 2 :(得分:2)

唯一的代码对我来说适用于 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);

感谢@AndyLin的回答和这个You can read the docs here

答案 3 :(得分:0)

VolkerK完全正确,但我的经验表明,发送文件“@”运算符只能用于数组。

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

现在您可以使用CURLOPT_POSTFIELDS

发送文件了

答案 4 :(得分:0)

林书豪(Andy Lin)所使用的方法由于某种原因对我不起作用,所以我找到了这种方法:

function makeCurlFile($file){
    $mime = mime_content_type($file);
    $info = pathinfo($file);
    $name = $info['basename'];
    $output = new CURLFile($file, $mime, $name);
    return $output;
}

通过将值与$ data有效负载中的键相关联,您可以发送其他内容,而不仅仅是文件,如下所示:

$ch = curl_init("https://api.example.com");
$mp3 =makeCurlFile($audio);
$photo = makeCurlFile($picture);
$data = array('mp3' => $mp3, 'picture' => $photo, 'name' => 'My latest single', 
'description' => 'Check out my newest song');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (curl_errno($ch)) {
   $result = curl_error($ch);
}
curl_close ($ch);

我认为这是由于某些API出于安全原因不支持使用旧方法的事实。

答案 5 :(得分:0)

我使用这种从 HTML 表单发送照片的方法

$ch = curl_init();

$cfile = new CURLFile($_FILES['resume']['tmp_name'], $_FILES['resume']['type'], $_FILES['resume']['name']);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $cfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);