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

2021-07-09 16:12:20 字數 1673 閱讀 5089

上傳檔案不存在。

搞了半天,最後是php版本不相容問題

上傳**

$data = array('media' => '@' . $img);

$ch = curl_init();

curl_setopt($ch, curlopt_url, $url);

curl_setopt($ch, curlopt_customrequest, 'post');

curl_setopt($ch, curlopt_ssl_verifypeer, false);

curl_setopt($ch, curlopt_ssl_verifyhost, false);

curl_setopt($ch, curlopt_useragent, 'mozilla/5.0 (compatible; msie 5.01; windows nt 5.0)');

curl_setopt($ch, curlopt_followlocation, 1);

curl_setopt($ch, curlopt_autoreferer, 1);

curl_setopt($ch, curlopt_postfields, $data);

curl_setopt($ch, curlopt_returntransfer, true);

$info = curl_exec($ch);

curl_close($ch);

此**在php5.6以前的版本都可以正常上傳,但是php 5.6拋棄了@語法,只支援 curlfile 方法上傳。這種

語言設計不向後相容我也是醉了。

5.6上傳這樣寫

$data = array('media' => new curlfile(realpath($tmp_name)));

另外也可以自己設計相容方法:

if(version_compare(phpversion(),'5.5.0') >= 0 && class_exists('curlfile'))else

另外的另外,還可以配置乙個curl引數來解決這個問題:

curl_setopt( $ch, curlopt_safe_upload, false);

這句要放到

curl_setopt($ch, curlopt_postfields, $data);之前

該設定官方說明

true to disable support for the @ prefix for uploading files in curlopt_postfields, 

which means that values starting with @ can be safely passed as fields. curlfile may be used for uploads instead.

added in php 5.5.0 with false as the default value. php 5.6.0 changes the default value to true.

大致意思設定為true時禁止@語法在curlopt_postfields上傳檔案,使用curlfile最為替代進行檔案上傳。

5.5版本增加該引數,php5.5預設是false,php5.6修改該預設值為true

官方參考

PHP curl 上傳檔案

檔案上傳 上傳檔案和前面的post十分相似。因為所有的檔案上傳表單都是通過post方法提交的。首先新建乙個接收檔案的頁面,命名為 upload output.php print r files 以下是真正執行檔案上傳任務的指令碼 以下為引用的內容 要上傳的本地檔案位址 upload c wamp w...

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...