[英]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¶2=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.