PHP curl 上傳檔案

2021-06-29 12:42:25 字數 1842 閱讀 6864

檔案上傳

上傳檔案和前面的post十分相似。因為所有的檔案上傳表單都是通過post方法提交的。

首先新建乙個接收檔案的頁面,命名為 upload_output.php:

print_r($_files);

以下是真正執行檔案上傳任務的指令碼:

以下為引用的內容:

// 要上傳的本地檔案位址

"upload" => "@c:/wamp/www/test.zip"    // linux 平台 這用方式 @/absolute/path/to/image.png

);$ch = curl_init();

curl_setopt($ch, curlopt_url, $url);

curl_setopt($ch, curlopt_returntransfer, 1);

curl_setopt($ch, curlopt_post, 1);

curl_setopt($ch, curlopt_postfields, $post_data);

$output = curl_exec($ch);

curl_close($ch);

echo $output;

如果你需要上傳乙個檔案,只需要把檔案路徑像乙個post變數一樣傳過去,不過記得在前面加上@符號。執行這段指令碼應該會得到如下輸出:

用post方法傳送資料

當發起get請求時,資料可以通過「查詢字串」(query string)傳遞給乙個url。例如,在google中搜尋時,搜尋關鍵即為url的查詢字串的一部分:

這種情況下你可能並不需要curl來模擬。把這個url丟給「file_get_contents()」就能得到相同結果。

不過有一些html表單是用post方法提交的。這種表單提交時,資料是通過 http請求體(request body) 傳送,而不是查詢字串。例如,當使用codeigniter論壇的表單,無論你輸入什麼關鍵字,總是被post到如下頁面:

你可以用php指令碼來模擬這種url請求。首先,新建乙個可以接受並顯示post資料的檔案,我們給它命名為post_output.php:

print_r($_post);

接下來,寫一段php指令碼來執行curl請求:

以下為引用的內容:

// 我們在post資料哦!

curl_setopt($ch, curlopt_post, 1);

// 把post的變數加上

curl_setopt($ch, curlopt_postfields, $post_data);

$output = curl_exec($ch);

curl_close($ch);

echo $output;

執行**後應該會得到以下結果:

這段指令碼傳送乙個post請求給 post_output.php ,這個頁面 $_post 變數並返回,我們利用curl捕捉了這個輸出。

PHP curl 上傳檔案 流

在執行過程中,以下兩種方式要看你的php 版本 file filepath file new curlfile realpath filepath 本次測試是在 php 5.6 如下 從可靠的角度,推薦指定curl safe upload的值,明確告知php是容忍還是禁止舊的 語法。注意在低版本ph...

php CURL上傳本地檔案

token x url token.type image function post url,data json encode true else else curl setopt curl,curlopt timeout,300 設定超時限制防止死迴圈 curl setopt curl,curlo...

PHP curl 上傳檔案版本相容問題

上傳檔案不存在。搞了半天,最後是php版本不相容問題 上傳 data array media img ch curl init curl setopt ch,curlopt url,url curl setopt ch,curlopt customrequest,post curl setopt c...