php5 6及以上版本利用curl檔案上傳

2022-08-31 16:24:12 字數 1421 閱讀 7326

php的curl支援通過給curl_postfields傳遞關聯陣列(而不是字串)來生成multipart/form-data的post請求。

傳統上,php的curl支援通過在陣列資料中,使用「@+檔案全路徑」的語法附加檔案,供curl讀取上傳。這與命令列直接呼叫curl程式的語法是一致的:

curl_setopt(ch, curlopt_postfields, array(

'file' => '@'.realpath('image.png'),

));

equals

$ curl -f "file=@/absolute/path/to/image.png"

但php從5.5開始引入了新的curlfile類用來指向檔案。curlfile類也可以詳細定義mime型別、檔名等可能出現在multipart/form-data資料中的附加資訊。php推薦使用curlfile替代舊的@語法:

curl_setopt(ch, curlopt_postfields, [

'file' => new curlfile(realpath('image.png')),

]);

php 5.5另外引入了curl_safe_upload選項,可以強制php的curl模組拒絕舊的@語法,僅接受curlfile式的檔案。5.5的預設值為false,5.6的預設值為true。

但是坑的一點在於:@語法在5.5就已經被打了deprecated,在5.6中就直接被刪除了(會產生 erorexception: the usage of the@filenameapi for file uploading is deprecated. please use the curlfile class instead)。

對於php 5.6+而言,手動設定curl_safe_upload為false是毫無意義的。根本不是字面意義理解的「設定成false,就能開啟舊的unsafe的方式」——舊的方式已經作為廢棄語法徹底不存在了。php 5.6+ == curlfile only,不要有任何的幻想。

我的部署環境是5.4(僅@語法),但開發環境是5.6(僅curlfile)。都沒有壓在5.5這個兩者都支援過渡版本上,結果就是必須寫出帶有環境判斷的兩套**。

環境判斷的**:

if (version_compare(phpversion(), '5.4.0') >= 0)   可以使用 但不推薦,畢竟帶有魔法數字

最後感謝,

這篇部落格

PHP5 6版本安裝redis擴充套件

一.php安裝redis擴充套件 1.使用phpinfo 函式檢視php的版本資訊,這會決定擴充套件檔案版本 3.解壓縮後,將php redis.dll和php igbinary.dll拷貝至php的ext目錄下 4.修改php.ini,在該檔案中加入 php redis extension php...

PHP5 6版本安裝redis擴充套件

一.php安裝redis擴充套件 1.使用phpinfo 函式檢視php的版本資訊,這會決定擴充套件檔案版本 2.根據php版本號,編譯器版本號和cpu架構,選擇php redis 2.2.5 5.6 ts vc11 x64.zip和php igbinary 1.2.1 5.5 ts vc11 x6...

PHP5 6版本安裝redis擴充套件

由 被刻印的時光 提交於 2020 12 09 20 10 40 一.php安裝redis擴充套件 1.使用phpinfo 函式檢視php的版本資訊,這會決定擴充套件檔案版本 2.根據php版本號,編譯器版本號和cpu架構,選擇php redis 2.2.5 5.6 ts vc11 x64.zip和...