php curl 上傳檔案代碼執行個體
這篇文章主要介紹了php curl 上傳檔案代碼執行個體,本文給出了兩種實現方法,並分別給出了實現代碼,需要的朋友可以參考下
假設server端上傳檔案處理指令碼upload.php:
代碼如下:
print_r($_POST);
print_r($_FILES);
1、使用 CURL 預設的方法
複製代碼 代碼如下:
//如果php檔案是utf8編碼,系統是GBK編碼,那麼就需要轉下編碼,要不然Php在系統中找不到這個檔案
$file = realpath(mb_convert_encoding('測試圖片.JPG','GBK','utf8'));
$file = realpath('temp.jpg'); //要上傳的檔案
$fields['f'] = '@'.$file; // 前面加@符表示上傳圖片
$ch =curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$content = curl_exec($ch);
echo $content;
2、另類的做法,有時我們需要將動態產生的內容當做檔案上傳到遠程伺服器,卻又不想在本機伺服器中構建臨時檔案。這樣就有了這個另類的寫法
代碼如下:
$contents =<<< 'TEXT'
這裡是檔案內容,也可以是圖片二進位,圖片需要修改上傳檔案類型
TEXT;
$varname = 'my';//上傳到$_FILES數組中的 key
$name = '3.txt';//檔案名稱
$type = 'text/plain';//檔案類型
$key = "$varname\"; filename=\"$name\r\nContent-Type: $type\r\n";
$fields[$key] = $contents;
$ch =curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$content = curl_exec($ch);
echo $content;
http://www.bkjia.com/PHPjc/990996.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/990996.htmlTechArticlephp curl 上傳檔案代碼執行個體 這篇文章主要介紹了php curl 上傳檔案代碼執行個體,本文給出了兩種實現方法,並分別給出了實現代碼,需要的朋友可以參...