Troubleshooting of curl errors in Mandarin

From LemonWiki共筆
Jump to navigation Jump to search

cUrl 是在命令行或腳本中用來傳輸資料的工具。(來源:cUrl 官網)(替代函式庫:(1) PHP 原生的 Client URL Library (2) PHP 的 cURL 類別 (3) 在 Windows 上透過 Cygwin 安裝 cUrl

🌐 Switch language: EN, 漢字


Owl icon.jpg 如何除錯 cUrl 命令:(1) 啟用 詳細模式 例如:「... 使用 -v / --verbose 選項執行命令以獲取更多資訊。」或 (2) 啟用 追蹤選項 例如:--trace-ascii [檔案名] 注意:如果同時啟用詳細模式和追蹤選項,詳細模式將覆蓋追蹤選項。

Curl 問題清單[edit]

如何解決命令執行問題:在 DOS/終端機中可以運作,但在 PHP 中不運作[edit]

手動在 DOS 或 Windows 終端機(如 ConEmu) 中執行命令時可以運作,但透過 PHP 執行時可能不會產生預期的結果。常見的問題是命令沒有生成預期的檔案。

Windows 終端機的範例 cURL 命令

curl "https://www.example.com/path/to/resource/" ^
-H "authority: www.example.com" ^
-H "accept: text/html" ^
--data-raw "PARAMS" --compressed > output.html

解決方案:為 PHP 修訂的 cURL 命令

curl "https://www.example.com/path/to/resource/" -H "authority: www.example.com" -H "accept: text/html" --data-raw "PARAMS" > output.html

方案解釋

  • Single Continuous String in PHP: In PHP, when executing a shell command, avoid using the caret (^) for multi-line commands[1], which is typical in the Command Prompt. Instead, ensure the command is one continuous string.
  • Unsupported curl Options: If you encounter an error like "curl: option --compressed: the installed libcurl version doesn't support this", it's a clear indication to remove or adjust the problematic option in the curl command.


如何解決 cUrl error (3) bad range in URL position xx[edit]

問題 當使用 curl 下載包含特殊字符(如 `[]`)的 URL 時,你可能會遇到這個錯誤:

curl: (3) bad range in URL position 33

解決方法 將特殊字符轉換為 URL 編碼格式:

# 錯誤示範
curl "https://example.com/api?param[0]=value"

# 正確示範
curl "https://example.com/api?param%5B0%5D=value"

常見的 URL 編碼對照:

  • `[` 轉換為 `%5B`
  • `]` 轉換為 `%5D`
  • 空格轉換為 `%20`

說明

  • URL 規範要求某些特殊字符必須經過編碼才能使用
  • 像 `[]` 這樣的字符在 URL 中有特殊含義,直接使用可能會導致解析錯誤
  • URL 編碼確保這些特殊字符能被正確傳輸和解析

如果你不確定是否需要編碼,可以使用線上 URL 編碼工具進行轉換,例如:URL 線上編碼和解碼工具

如何解決 cUrl 錯誤 (#5): 不支援的代理語法 (Unsupported proxy syntax)[edit]

問題狀況:socks5 代理的使用者名稱包含 @ 符號,例如 [email protected]

curl_setopt($ch, CURLOPT_PROXY, 'socks5://username:password@localhost:12345');
// result is ok

curl_setopt($ch, CURLOPT_PROXY, 'socks5://[email protected]:password@localhost:12345');
// met cUrl error (#5): Unsupported proxy syntax

解決方案

curl_setopt($ch, CURLOPT_PROXY, 'socks5://bob%40email.com:password@localhost:12345');
// result is ok

可以使用 URL Encode and Decode - Onlineurlencode 函數,跳脫 (Escape) 特殊符號[2]

如何解決 cUrl 錯誤 (#56):OpenSSL SSL_read: No error.[edit]

錯誤條件:Windows 上的 curl 版本 7.67.0 遇到問題。[curl_version](https://www.php.net/manual/en/function.curl-version.php) 返回的結果:

version: Array
(
    [version_number] => 475904
    [age] => 5
    [features] => 2953117
    [ssl_version_number] => 0
    [version] => 7.67.0
    [host] => x86_64-pc-win32
    [ssl_version] => OpenSSL/1.1.1d
    [libz_version] => 1.2.11
)

解決方案: 使用其他版本的 curl command or curl on Cygwin or cURL class for PHP.

相關文章


如何解決錯誤:error code: 1010[edit]

識別問題

  • 當我試圖透過 cURL 命令下載網頁內容時,遇到了一個問題,輸出顯示為「error code: 10100」。為了探索原因,重新執行了cURL命令並啟動了詳細模式(使用 -v 旗標)。顯示的標頭資訊包括:
< report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=xxx"}],"group":"cf-nel","max_age":604800}
< nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
< server: cloudflare

建議解決方案

  • 建議改成使用 JavaScript 基礎的爬蟲 (JavaScript-bases browser) 來代替 cURL 命令的方案 [3]

如何解決 400 Bad Request 錯誤:UTF-8 字元編碼問題[edit]

問題分析:

遇到錯誤的 macOS 終端機 cURL 命令:

$ curl "https://api.search.brave.com/res/v1/web/search?q=\"XXX\"+公司簡介+產品+服務" \
 -H "Accept: application/json" \
 -H "Accept-Encoding: gzip" \
 -H "X-Subscription-Token: YOUR_API_KEY_HERE"

> <html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>

解決方案

正確處理 URL 編碼:中文字元和特殊符號需要正確進行 URL 編碼以避免 400 Bad Request 錯誤(線上工具:URL Encode and Decode - Online):

  • "XXX"%22XXX%22
  • 公司簡介%E5%85%AC%E5%8F%B8%E7%B0%A1%E4%BB%8B
  • 產品%E7%94%A2%E5%93%81
  • 服務%E6%9C%8D%E5%8B%99

修正後的 cURL 命令:

$ curl "https://api.search.brave.com/res/v1/web/search?q=%22XXX%22+%E5%85%AC%E5%8F%B8%E7%B0%A1%E4%BB%8B+%E7%94%A2%E5%93%81+%E6%9C%8D%E5%8B%99" \
 -H "Accept: application/json"  \
 -H "Accept-Encoding: gzip" \
 -H "X-Subscription-Token: YOUR_API_KEY_HERE"

如何解決錯誤 405 Method Not Allowed[edit]

當我嘗試爬取網路資源但遇到錯誤訊息:"錯誤 405 方法不允許"

解決方案:

  • 確保使用正確的 HTTP 請求方法 e.g. GETPOST 來存取網路資源。

如何解決錯誤 415 Unsupported Media Type[edit]

當我嘗試 POST JSON(作為有效負載)但遇到錯誤訊息:"錯誤 415 不支援的媒體類型"

解決方案:

  • 設定 cUrl 的標頭 (header) Content-Type: application/json [4]例如 cUrl 命令的語法如下:
curl -X POST --header "Content-Type: application/json" --data '{"user" : "your_user_name", "token" : "your_token"}' "https://example.com/"

如何解決 cURL 返回二進位資料,而非 html 或 json[edit]

如何解決下載的檔案是空的[edit]

錯誤條件

  • 當我執行了 Curl 命令 curl -O https://path/to/plain_text.txt,但下載的檔案是空的。
  • 啟用 詳細模式 後,發現了 HTTP 狀態碼 HTTP/1.1 302 Moved Temporarily。我添加了位置(-L)參數來解決下載的檔案是空的問題
執行命令結果: curl -v -O https://path/to/plain_text.txt

< HTTP/1.1 302 Moved Temporarily
< Server: nginx
< Date: Tue, 25 Aug 2020 03:45:13 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=60
< Location: /path/to/plain_text.txt

解決方案

curl -L -O https://path/to/plain_text.txt

如何解決錯誤:no matches found[edit]

錯誤條件

  • 當我執行了 Curl 命令 curl http://website.test/http_status.php?case=500,但我遇到了錯誤訊息:"zsh: 未找到匹配:http://website.test/http_status.php?case=500"

解決方案

  • 雙引號包住 URL e.g. curl "http://website.test/http_status.php?case=500"

相關資料

如何解決錯誤:Remote file name has no length[edit]

錯誤訊息

curl -O "https://website.com/?p=123"
curl: Remote file name has no length
curl: (23) Failed writing received data to disk/application

解決方案

curl "https://website.com/?p=123" -o myfile.html 

解決方案解釋

  • 當你在下載檔案時遇到錯誤,可能是因為 URL 不包含檔案名稱,導致 `curl` 無法確定要保存檔案的名稱。解決方案是使用 `-o` 選項手動指定檔案名稱,例如,`curl -o myfile.html "https://website.com/?p=123"`。此外,確保你有足夠的磁碟空間並且在你有寫入權限的目錄中。


如何解決 zsh: parse error near `&' 錯誤[edit]

錯誤狀況

% curl -XPOST http://localhost:3000/ -H "Content-Type: application/json"  -d'{"url": "https://someweb.com/Today's_Biggest_Trends"}'
dquote>

解決方案: 跳脫單引號,例如' 改成 '' (單引號重複兩次)

% curl -XPOST http://localhost:3000/ -H "Content-Type: application/json"  -d'{"url": "https://someweb.com/Today''s_Biggest_Trends"}'

Trivial Solution Icon_exclaim.gif NOT WORK: single quote ' became \'

% curl -XPOST http://localhost:3000/ -H "Content-Type: application/json"  -d'{"url": "https://someweb.com/Today\'s_Biggest_Trends"}'
dquote>

如何解決 zsh Event Not Found 錯誤[edit]

在 zsh shell 中執行包含 JSON 資料的 cURL 命令時,你可能會遇到以下錯誤訊息:

> zsh: event not found: \

這是因為 zsh 將驚嘆號 (!) 解釋為歷史展開字元,即使它出現在雙引號內也是如此。

要解決此錯誤,可以使用以下任一方法:

方法 1:對 JSON 資料使用單引號 -d '{"message": "Hello '\''world'\'' & welcome!", "price": "$19.99"}'

方法 2:跳脫驚嘆號 -d "{\"message\": \"Hello 'world' & welcome\!\", \"price\": \"\$19.99\"}"

方法 3:使用 heredoc 搭配 stdin -d @- << 'EOF'

方法 4:將 JSON 儲存到檔案並引用 -d @payload.json

方法 5:暫時停用歷史展開功能[5] set +H (在命令之前執行)

修正語法的範例:

使用單引號:

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello '\''world'\'' & welcome!", "price": "$19.99"}' \
  -v \
  https://example.com/api/

使用 heredoc(建議用於複雜的 JSON):

curl -X POST \
  -H "Content-Type: application/json" \
  -d @- \
  -v \
  https://example.com/api/ << 'EOF'
{
  "message": "Hello 'world' & welcome!",
  "price": "$19.99",
  "special_chars": "!@#$%^&*()_+{}|:<>?[]\\;'\",./"
}
EOF

使用外部 JSON 檔案:

curl -X POST \
  -H "Content-Type: application/json" \
  -d @payload.json \
  -v \
  https://example.com/api/

注意:建議使用 heredoc 方法來處理複雜的 JSON,因為它可以避免所有 shell 解釋問題並保持可讀的格式。

如何隱藏進度條[edit]

執行 curl 命令時,通常會輸出詳細的下載和上傳進度資訊,如下所示:

 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 90141  100 90141    0     0  20029      0  0:00:04  0:00:04 --:--:-- 22012

要隱藏 curl 命令的進度條,你可以使用 `-s`(silent)選項來隱藏所有輸出,或使用 `-S`(silent with error messages)選項來隱藏進度條但仍顯示錯誤訊息。

curl -sS [URL]

或者,如果你想隱藏所有輸出包括錯誤訊息,只需使用 `-s`(silent)選項: ``` curl -s [URL] ```

如何解決 cURL 非法檔名字元錯誤[edit]

執行包含非法字元的輸出檔名的 cURL 指令時,可能會遇到以下錯誤訊息:

curl -o $'example\ntest.html' http://example.com

Warning: Failed to open the file $'example\ntest.html': No such file or
Warning: directory
curl: (23) client returned ERROR on write of 1256 bytes

要解決此錯誤,請在cURL 指令的 -o--output 參數中使用有效的檔名字元:

  • 移除非法字元,如:< > : " | ? * \ 以及控制字元
  • 避免路徑分隔符號:/(除非要建立目錄)
  • 使用安全字元:a-z A-Z 0-9 - _ .
  • 如有需要請先建立目錄:mkdir -p directory

Windows 與 Mac/Linux 系統的 cURL JSON 傳遞問題[edit]

1. 問題 在 Windows 系統執行 cURL 命令時遇到以下錯誤:

Invalid JSON payload received. Unknown name "": Root element must be a message.

2. 解決方案 Windows 系統:

curl -X POST -H "Content-Type: application/json" "API_URL" -d "{\"key\":\"value\"}"

Mac/Linux 系統:

curl -X POST -H "Content-Type: application/json" "API_URL" -d '{"key":"value"}'

PHP 程式碼:

$is_windows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
if ($is_windows) {
    $command = sprintf('-d "{\"key\":\"%s\"}"', $value);
} else {
    $command = sprintf("-d '%s'", $json_payload);
}

3. 問題說明

  • 根本原因:Windows 和 Mac/Linux 處理 shell 命令中的引號方式不同
  • Windows:需要使用雙引號並轉義內部的引號
  • Mac/Linux:可以使用單引號包住完整的 JSON 字串
  • 當使用不當的引號格式時,JSON payload 會被錯誤解析,導致 API 回傳格式錯誤的訊息

相關資安議題[edit]

  • Command Injection 「指令注入 (Command Injection) 是一種攻擊手法,攻擊者會利用應用程式中的漏洞,注入並執行惡意的作業系統指令,通常是透過未經驗證的使用者輸入,例如表單、Cookie 或 HTTP 標頭等方式傳入。」

延伸閱讀[edit]

References[edit]


Troubleshooting of ...

Template