PHP:curl模擬form表單上傳檔案
阿新 • • 發佈:2018-12-25
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<buttion>submit</button>
</form>
需要模擬的就是上面form表單。
-
正文的開始
// form.php /** * curl Post檔案,php5以下版本可用 * * @param $action (處理上傳檔案的url,form表單的action) * @param $path (檔案路徑) **/ function upload_file($action, $path){ $data = array( // 需要注意的是,在路徑前必須帶上@,不然只會當做是簡單的鍵值對 'pic' => '@'.realpath($path) 'name' => 'issac' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $action); curl_setopt($ch, CURLOPT_POST, true ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //該curl_setopt可以向header寫鍵值對 curl_setopt($ch, CURLOPT_HEADER, false); // 不返回頭資訊 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); return $output; } // 呼叫 upload_file('accrpt.php', '/files/img.png');
// accept.php
print_r($_FILES); // 輸出上傳到伺服器的臨時檔案的資訊
print_r($_POST); // name => issac
PS:上面例子只有在php5以下版本有效,換言之現在根本沒有用 根本沒有用 根本沒有用 [手動摔桌子],而且現在網上充斥的全是這種過時的失效版本
@字元什麼,現在根本沒有用了,不要懷疑你自己,還有網上說只要加上:
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
就能起效,不用懷疑,這也是沒有效的[手動摔桌子],這個選項已經棄用了,現在。
Paste_Image.png
Paste_Image.png
-
以下才是現在真實有效的做法:
用curlFile代替@,也不需要使用 CURLOPT_SAFE_UPLOAD
用
$data = array(
'pic'=>new CURLFile($path)
// 如果無效可以這樣
// 'pic'=>curl_file_create($path)
);
替換
$data = array(
'pic'=>'@'.realpath($path)
);
Paste_Image.png