【问题标题】:why can't curl download the same URL in different format?为什么 curl 不能以不同的格式下载相同的 URL?
【发布时间】:2010-01-06 20:07:06
【问题描述】:

卷曲下载http://mysite.com/Lunacy%20Disc%202%20of%202%20(U)(Saturn).zip

但不是

http://mysite.com/Lunacy Disc 2 of 2 (U)(Saturn).zip

为什么会这样?

我需要将其转换为第一种格式吗?

使用通过 urlencode($url) 生成的 URL 失败。

【问题讨论】:

    标签: php curl


    【解决方案1】:

    两个问题:

    1. urlencode 也会对你身上的斜线进行编码。它旨在编码查询字符串以用于 url,而不是完整的 url。
    2. urlencode 将空格编码为+。如果您想要空格为%20,则需要rawurlencode

    【讨论】:

      【解决方案2】:

      要将 URL 转换为“第一种格式”,您可以使用 PHP 函数 urlencode


      现在,对于“为什么”,答案大概可以在RFC 1738 - Uniform Resource Locators (URL)找到。

      引用一些段落:

      Octets must be encoded if they have no corresponding graphic
      character within the US-ASCII coded character set, if the use of the
      corresponding character is unsafe, or if the corresponding character
      is reserved for some other interpretation within the particular URL
      scheme.
      
      No corresponding graphic US-ASCII:
      
      URLs are written only with the graphic printable characters of the
      US-ASCII coded character set. The octets 80-FF hexadecimal are not
      used in US-ASCII, and the octets 00-1F and 7F hexadecimal represent
      control characters; these must be encoded.
      

      空格的代码为 %20 -- 它不在 00-1F 范围内,因此应该为此进行编码...但是,稍后:

      Unsafe:
      
         Characters can be unsafe for a number of reasons.  The space
         character is unsafe because significant spaces may disappear and
         insignificant spaces may be introduced when URLs are transcribed or
         typeset or subjected to the treatment of word-processing programs.
      

      在这里,您知道为什么也必须对空格字符进行转义/编码;-)

      【讨论】:

        【解决方案3】:

        urlencode() 确实会因 curl 而失败,如果您的问题只是空格,您可以手动替换它们

        $url = str_replace(' ', '%20', $url);
        

        【讨论】:

          【解决方案4】:

          您需要 urlencode 来翻译空格(在您的示例中;还有其他需要它的字符)以通过 Internet 传输。编码确保各种通信协议在处理字符串时不会终止或以其他方式破坏字符串。

          【讨论】:

            【解决方案5】:

            http://mysite.com/Lunacy Disc 2 of 2 (U)(Saturn).zip

            这不是一个有效的网址。像这样访问 url 可能在您的浏览器中工作,因为大多数现代浏览器会在需要时自动为您编码 url。 curl 库不能自动执行此操作。

            【讨论】:

              【解决方案6】:

              为什么?因为某些字符具有特殊含义,例如#(html 锚点)。

              所以除了字母数字的所有字符都被编码,无论是否需要编码。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2014-05-20
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多