繁体   English   中英

CURL PHP 发送图片

[英]CURL PHP send image

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

有多种使用 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

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

CURLOPT_POSTFIELDS要在 HTTP“POST”操作中发布的完整数据。 , prepend a filename with @ and use the full path. ,请在文件名前加上 @ 并使用完整路径。 这既可以作为 urlencoded 字符串(如 'para1=val1&para2=val2&...')传递,也可以作为以字段名称作为键和字段数据作为值的数组传递。 如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data。

唯一的代码适用于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 的回答和这个来源

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 出于安全原因不支持旧的方式。

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

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

现在您可以使用CURLOPT_POSTFIELDS发送文件

我使用这种从 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM