Editing
Troubleshooting of curl errors in Mandarin
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
[https://curl.haxx.se/ cUrl] 是在命令行或腳本中用來傳輸資料的工具。(來源:[https://curl.haxx.se/ cUrl 官網])(替代函式庫:(1) PHP 原生的 [https://www.php.net/manual/en/book.curl.php Client URL Library] (2) [https://packagist.org/packages/curl/curl PHP 的 cURL 類別] (3) [https://www.oracle.com/webfolder/technetwork/tutorials/obe/cloud/objectstorage/installing_cURL/installing_cURL_on_Cygwin_on_Windows.html 在 Windows 上透過 Cygwin 安裝 cUrl] {{LanguageSwitcher | content = [[Troubleshooting of curl errors | EN]], [[Troubleshooting of curl errors in Mandarin | 漢字]] }} {{Tips}} 如何除錯 cUrl 命令:(1) 啟用 [https://ec.haxx.se/usingcurl/verbose 詳細模式] 例如:「... 使用 {{kbd | key=<nowiki>-v</nowiki>}} / {{kbd | key=<nowiki>--verbose</nowiki>}} 選項執行命令以獲取更多資訊。」或 (2) 啟用 [https://ec.haxx.se/usingcurl/verbose/trace 追蹤選項] 例如:{{kbd | key=<nowiki>--trace-ascii [檔案名]</nowiki>}} 注意:如果同時啟用詳細模式和追蹤選項,詳細模式將覆蓋追蹤選項。 == Curl 問題清單 == === 如何解決命令執行問題:在 DOS/終端機中可以運作,但在 PHP 中不運作 === 手動在 DOS 或 Windows 終端機(如 [https://conemu.github.io/ ConEmu]) 中執行命令時可以運作,但透過 PHP 執行時可能不會產生預期的結果。常見的問題是命令沒有生成預期的檔案。 Windows 終端機的範例 cURL 命令 <pre> curl "https://www.example.com/path/to/resource/" ^ -H "authority: www.example.com" ^ -H "accept: text/html" ^ --data-raw "PARAMS" --compressed > output.html </pre> 解決方案:為 PHP 修訂的 cURL 命令 <pre> curl "https://www.example.com/path/to/resource/" -H "authority: www.example.com" -H "accept: text/html" --data-raw "PARAMS" > output.html </pre> 方案解釋 * '''Single Continuous String in PHP''': In PHP, when executing a shell command, avoid using the caret (^) for multi-line commands<ref>[https://stackoverflow.com/questions/69068/split-long-commands-in-multiple-lines-through-windows-batch-file/21000752#21000752 Split long commands in multiple lines through Windows batch file - Stack Overflow]</ref>, 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 === '''問題''' 當使用 curl 下載包含特殊字符(如 `[]`)的 URL 時,你可能會遇到這個錯誤: <pre> curl: (3) bad range in URL position 33 </pre> '''解決方法''' 將特殊字符轉換為 URL 編碼格式: <pre> # 錯誤示範 curl "https://example.com/api?param[0]=value" # 正確示範 curl "https://example.com/api?param%5B0%5D=value" </pre> 常見的 URL 編碼對照: * `[` 轉換為 `%5B` * `]` 轉換為 `%5D` * 空格轉換為 `%20` '''說明''' * URL 規範要求某些特殊字符必須經過編碼才能使用 * 像 `[]` 這樣的字符在 URL 中有特殊含義,直接使用可能會導致解析錯誤 * URL 編碼確保這些特殊字符能被正確傳輸和解析 如果你不確定是否需要編碼,可以使用線上 URL 編碼工具進行轉換,例如:[https://www.urlencoder.org/ URL 線上編碼和解碼工具]。 === 如何解決 cUrl 錯誤 (#5): 不支援的代理語法 (Unsupported proxy syntax) === 問題狀況:[https://en.wikipedia.org/wiki/SOCKS socks5] 代理的使用者名稱包含 @ 符號,例如 {{kbd | key=<nowiki>bob@email.com</nowiki>}} <pre> curl_setopt($ch, CURLOPT_PROXY, 'socks5://username:password@localhost:12345'); // result is ok curl_setopt($ch, CURLOPT_PROXY, 'socks5://bob@email.com:password@localhost:12345'); // met cUrl error (#5): Unsupported proxy syntax </pre> 解決方案 <pre> curl_setopt($ch, CURLOPT_PROXY, 'socks5://bob%40email.com:password@localhost:12345'); // result is ok </pre> 可以使用 [https://www.urlencoder.org/ URL Encode and Decode - Online] 或 [https://www.php.net/manual/en/function.urlencode.php urlencode] 函數,跳脫 (Escape) 特殊符號<ref>[https://superuser.com/questions/937124/log-in-to-ftp-using-windows-explorer-with-in-the-username Log in to FTP using Windows Explorer with @ in the username - Super User]</ref>。 === 如何解決 cUrl 錯誤 (#56):OpenSSL SSL_read: No error. === 錯誤條件:Windows 上的 curl 版本 7.67.0 遇到問題。[curl_version](https://www.php.net/manual/en/function.curl-version.php) 返回的結果: <pre> 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 ) </pre> 解決方案: 使用其他版本的 [https://curl.haxx.se/windows/ curl command] or curl on [https://www.cygwin.com/ Cygwin] or [https://packagist.org/packages/curl/curl cURL class for PHP]. 相關文章 * [https://github.com/curl/curl/issues/4982 cURL error 56: OpenSSL SSL_read: No error information · Issue #4982 · curl/curl] === 如何解決錯誤:error code: 1010 === 識別問題 * 當我試圖透過 cURL 命令下載網頁內容時,遇到了一個問題,輸出顯示為「error code: 10100」。為了探索原因,重新執行了cURL命令並啟動了詳細模式(使用 {{kbd | key=<nowiki>-v</nowiki>}} 旗標)。顯示的標頭資訊包括: <pre> < 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 </pre> 建議解決方案 * 建議改成使用 JavaScript 基礎的爬蟲 (JavaScript-bases browser) 來代替 cURL 命令的方案 <ref>[https://www.zenrows.com/blog/cloudflare-error-1010#how-to-avoid Cloudflare Error 1010: What Is It and How to Avoid - ZenRows]</ref>。 === 如何解決 400 Bad Request 錯誤:UTF-8 字元編碼問題 === '''問題分析:''' 遇到錯誤的 macOS 終端機 cURL 命令: <pre> $ 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> </pre> '''解決方案''' 正確處理 URL 編碼:中文字元和特殊符號需要正確進行 URL 編碼以避免 400 Bad Request 錯誤(線上工具:[https://www.urlencoder.org/ URL Encode and Decode - Online]): * {{kbd | key=<nowiki>"XXX"</nowiki>}} → {{kbd | key=<nowiki>%22XXX%22</nowiki>}} * {{kbd | key=<nowiki>公司簡介</nowiki>}} → {{kbd | key=<nowiki>%E5%85%AC%E5%8F%B8%E7%B0%A1%E4%BB%8B</nowiki>}} * {{kbd | key=<nowiki>產品</nowiki>}} → {{kbd | key=<nowiki>%E7%94%A2%E5%93%81</nowiki>}} * {{kbd | key=<nowiki>服務</nowiki>}} → {{kbd | key=<nowiki>%E6%9C%8D%E5%8B%99</nowiki>}} '''修正後的 cURL 命令:''' <pre> $ 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" </pre> === 如何解決錯誤 405 Method Not Allowed === 當我嘗試爬取網路資源但遇到錯誤訊息:"錯誤 405 方法不允許" 解決方案: * 確保使用正確的 HTTP 請求方法 e.g. {{kbd | key=GET}} 或 {{kbd | key=POST}} 來存取網路資源。 === 如何解決錯誤 415 Unsupported Media Type === 當我嘗試 POST JSON(作為有效負載)但遇到錯誤訊息:"錯誤 415 不支援的媒體類型" 解決方案: * 設定 cUrl 的標頭 (header) {{kbd | key=<nowiki>Content-Type: application/json</nowiki>}} <ref>[https://stackoverflow.com/questions/11087872/php-curl-post-returns-a-415-unsupported-media-type PHP cURL POST returns a 415 - Unsupported Media Type - Stack Overflow]</ref>例如 cUrl 命令的語法如下: <pre> curl -X POST --header "Content-Type: application/json" --data '{"user" : "your_user_name", "token" : "your_token"}' "https://example.com/" </pre> === 如何解決 cURL 返回二進位資料,而非 html 或 json === * [https://stackoverflow.com/questions/28283822/curl-returns-binary-data-instead-of-html php - cURL returns binary data instead of html - Stack Overflow] * [https://errerrors.blogspot.com/2020/06/resolve-curl-returns-binary-data-instead-of-html-or-json.html 解決 cUrl 下載的網頁或 JSON 看起來像是亂碼的問題] === 如何解決下載的檔案是空的 === 錯誤條件 * 當我執行了 Curl 命令 {{kbd | key=<nowiki>curl -O https://path/to/plain_text.txt</nowiki>}},但下載的檔案是空的。 * 啟用 [https://ec.haxx.se/usingcurl/usingcurl-verbose 詳細模式] 後,發現了 HTTP 狀態碼 {{kbd | key=HTTP/1.1 302 Moved Temporarily}}。我添加了位置([https://curl.haxx.se/docs/manpage.html#-L -L])參數來解決下載的檔案是空的問題 <pre> 執行命令結果: 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 </pre> 解決方案 <pre> curl -L -O https://path/to/plain_text.txt </pre> === 如何解決錯誤:no matches found === 錯誤條件 * 當我執行了 Curl 命令 {{kbd | key=<nowiki>curl http://website.test/http_status.php?case=500</nowiki>}},但我遇到了錯誤訊息:"zsh: 未找到匹配:<nowiki>http://website.test/http_status.php?case=500</nowiki>" 解決方案 * 雙引號包住 {{kbd | key=<nowiki>URL</nowiki>}} e.g. {{kbd | key=<nowiki>curl "http://website.test/http_status.php?case=500"</nowiki>}} 相關資料 * [https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E7%82%BA%E4%BB%80%E9%BA%BC-mac-terminal-curl-%E6%8C%87%E4%BB%A4%E7%9A%84%E7%B6%B2%E5%9D%80%E9%80%9A%E5%B8%B8%E8%A6%81%E5%8A%A0%E9%9B%99%E5%BC%95%E8%99%9F-8c3e9227be34 為什麼 Mac terminal curl 指令的網址通常要加雙引號 - 彼得潘的 Swift iOS App 開發問題解答集 - Medium] * Double quote the {{kbd | key=<nowiki>URL</nowiki>}} e.g. {{kbd | key=<nowiki>curl "http://website.test/http_status.php?case=500"</nowiki>}} === 如何解決錯誤:Remote file name has no length === 錯誤訊息 <pre> curl -O "https://website.com/?p=123" curl: Remote file name has no length curl: (23) Failed writing received data to disk/application </pre> 解決方案 <pre> curl "https://website.com/?p=123" -o myfile.html </pre> 解決方案解釋 * 當你在下載檔案時遇到錯誤,可能是因為 URL 不包含檔案名稱,導致 `curl` 無法確定要保存檔案的名稱。解決方案是使用 `-o` 選項手動指定檔案名稱,例如,`curl -o myfile.html "https://website.com/?p=123"`。此外,確保你有足夠的磁碟空間並且在你有寫入權限的目錄中。 === 如何解決 zsh: parse error near `&' 錯誤 === 錯誤狀況 <pre> % curl -XPOST http://localhost:3000/ -H "Content-Type: application/json" -d'{"url": "https://someweb.com/Today's_Biggest_Trends"}' dquote> </pre> 解決方案: 跳脫單引號,例如{{kbd | key=<nowiki>'</nowiki>}} 改成 {{kbd | key=<nowiki>''</nowiki>}} (單引號重複兩次) <pre> % curl -XPOST http://localhost:3000/ -H "Content-Type: application/json" -d'{"url": "https://someweb.com/Today''s_Biggest_Trends"}' </pre> Trivial Solution {{exclaim}} '''NOT WORK''': single quote {{kbd | key=<nowiki>'</nowiki>}} became {{kbd | key=<nowiki>\'</nowiki>}} <pre> % curl -XPOST http://localhost:3000/ -H "Content-Type: application/json" -d'{"url": "https://someweb.com/Today\'s_Biggest_Trends"}' dquote> </pre> === 如何解決 zsh Event Not Found 錯誤 === 在 zsh shell 中執行包含 JSON 資料的 cURL 命令時,你可能會遇到以下錯誤訊息: <pre> > zsh: event not found: \ </pre> 這是因為 zsh 將驚嘆號 (!) 解釋為歷史展開字元,即使它出現在雙引號內也是如此。 要解決此錯誤,可以使用以下任一方法: '''方法 1:對 JSON 資料使用單引號''' {{kbd | key=<nowiki>-d '{"message": "Hello '\''world'\'' & welcome!", "price": "$19.99"}'</nowiki>}} '''方法 2:跳脫驚嘆號''' {{kbd | key=<nowiki>-d "{\"message\": \"Hello 'world' & welcome\!\", \"price\": \"\$19.99\"}"</nowiki>}} '''方法 3:使用 heredoc 搭配 stdin''' {{kbd | key=<nowiki>-d @- << 'EOF'</nowiki>}} '''方法 4:將 JSON 儲存到檔案並引用''' {{kbd | key=<nowiki>-d @payload.json</nowiki>}} '''方法 5:暫時停用歷史展開功能'''<ref>[https://www.reddit.com/r/bash/comments/cl54to/not_sure_why_mac_is_saying_bash_event_not_found/?show=original not sure why mac is saying `-bash: !": event not found` when I try to simply echo a string containing a "!" : r/bash]</ref> {{kbd | key=<nowiki>set +H</nowiki>}} (在命令之前執行) 修正語法的範例: 使用單引號: <pre> curl -X POST \ -H "Content-Type: application/json" \ -d '{"message": "Hello '\''world'\'' & welcome!", "price": "$19.99"}' \ -v \ https://example.com/api/ </pre> 使用 heredoc(建議用於複雜的 JSON): <pre> 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 </pre> 使用外部 JSON 檔案: <pre> curl -X POST \ -H "Content-Type: application/json" \ -d @payload.json \ -v \ https://example.com/api/ </pre> 注意:建議使用 heredoc 方法來處理複雜的 JSON,因為它可以避免所有 shell 解釋問題並保持可讀的格式。 === 如何隱藏進度條 === 執行 curl 命令時,通常會輸出詳細的下載和上傳進度資訊,如下所示: <pre> % 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 </pre> 要隱藏 curl 命令的進度條,你可以使用 `-s`(silent)選項來隱藏所有輸出,或使用 `-S`(silent with error messages)選項來隱藏進度條但仍顯示錯誤訊息。 <pre> curl -sS [URL] </pre> 或者,如果你想隱藏所有輸出包括錯誤訊息,只需使用 `-s`(silent)選項: ``` curl -s [URL] ``` === 如何解決 cURL 非法檔名字元錯誤 === 執行包含非法字元的輸出檔名的 cURL 指令時,可能會遇到以下錯誤訊息: <pre> 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 </pre> 要解決此錯誤,請在cURL 指令的 {{kbd | key=<nowiki>-o</nowiki>}} 或 {{kbd | key=<nowiki>--output</nowiki>}} 參數中使用有效的檔名字元: * 移除非法字元,如:{{kbd | key=<nowiki>< > : " | ? * \</nowiki>}} 以及控制字元 * 避免路徑分隔符號:{{kbd | key=<nowiki>/</nowiki>}}(除非要建立目錄) * 使用安全字元:{{kbd | key=<nowiki>a-z A-Z 0-9 - _ .</nowiki>}} * 如有需要請先建立目錄:{{kbd | key=<nowiki>mkdir -p directory</nowiki>}} === Windows 與 Mac/Linux 系統的 cURL JSON 傳遞問題 === '''1. 問題''' 在 Windows 系統執行 cURL 命令時遇到以下錯誤: <pre> Invalid JSON payload received. Unknown name "": Root element must be a message. </pre> '''2. 解決方案''' Windows 系統: <pre> curl -X POST -H "Content-Type: application/json" "API_URL" -d "{\"key\":\"value\"}" </pre> Mac/Linux 系統: <pre> curl -X POST -H "Content-Type: application/json" "API_URL" -d '{"key":"value"}' </pre> PHP 程式碼: <pre> $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); } </pre> '''3. 問題說明''' * 根本原因:Windows 和 Mac/Linux 處理 shell 命令中的引號方式不同 * Windows:需要使用雙引號並轉義內部的引號 * Mac/Linux:可以使用單引號包住完整的 JSON 字串 * 當使用不當的引號格式時,JSON payload 會被錯誤解析,導致 API 回傳格式錯誤的訊息 == 相關資安議題 == * [https://owasp.org/www-community/attacks/Command_Injection Command Injection] 「指令注入 (Command Injection) 是一種攻擊手法,攻擊者會利用應用程式中的漏洞,注入並執行惡意的作業系統指令,通常是透過未經驗證的使用者輸入,例如表單、Cookie 或 HTTP 標頭等方式傳入。」 == 延伸閱讀 == * [https://ec.haxx.se/ Introduction - Everything curl] * [https://curl.haxx.se/docs/manpage.html curl - How To Use] * [https://stackoverflow.com/questions/32122586/curl-escape-single-quote bash - CURL escape single quote - Stack Overflow] == References == <references /> {{Template:Troubleshooting}} [[Category: Web server]] [[Category: Programming]] [[Category: Web scraping]] [[Category: Revised with LLMs]]
Summary:
Please note that all contributions to LemonWiki共筆 are considered to be released under the Creative Commons Attribution-NonCommercial-ShareAlike (see
LemonWiki:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Templates used on this page:
Template:Exclaim
(
edit
)
Template:Kbd
(
edit
)
Template:LanguageSwitcher
(
edit
)
Template:Tips
(
edit
)
Template:Troubleshooting
(
edit
)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Current events
Recent changes
Random page
Help
Categories
Tools
What links here
Related changes
Special pages
Page information