URL中包含特殊字符的HTTP状态代码


HTTP status code with special characters in the URL

我有一个用JavaScript和PHP编写的小工具,它可以获取URL列表并检查所有URL的HTTP状态代码。我用curl来检查实际状态
只要我有漂亮的URL,它就很好用。我的URL中有®时遇到问题。我的工具在知道应该返回301时返回404

我的猜测是,这个"®"正在被转换为类似%C2的东西,并导致了一个问题。

我知道这是可以做到的,因为在这里粘贴相同的URL会返回301

我的PHP卷曲看起来像这样:

        ...
        if (($curl = curl_init()) == false) {
            throw new Exception('curl_init error for url '.$_POST['url'].'.');
        }
        $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: iso-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-US;q=0.5";
        $header[] = "Pragma: ";
        
        curl_setopt($curl, CURLOPT_URL, $_POST['url']);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 50);
        $Cresponse = curl_exec($curl); // execute the curl command
        $response['callback']['data'] = $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        ...

我尝试使用urldecode(),但这将对整个URL以及http://http%3A%2F%2F进行编码。

知道为什么这个®会引起问题吗?

仅使用parse_url()和urlencode()作为pathqueryfragment

然后重新组装编码的URL并发出请求。

$url = parse_url ($_POST['url']);
if ($url === FALSE) {
    /* error handling */
}
$encoded_url = $url['scheme'] . "://" .
               $url['host']   .
               urlencode ($url['path])     . "?"   .
               urlencode ($url['query])    . "#"   .
               urlencode ($url['fragment])

Javascript方面,您需要使用encodeURI函数来转义url,如下所示:

// results in "http://test.com?var=%C2%AE"
$url = encodeURI("http://test.com?var=®")

然后,在PHP方面,在使用它之前,您需要像这样用urldecode对它进行Unscape:

$url = urldecode($_POST['url']);

如果这仍然不起作用,请将url参数记录到文件中,或者输出它并使用浏览器控制台进行检查。

这取决于服务器期望如何接收URL。URL只能由ASCII字符的子集组成。"®"肯定不在该子集内,需要进行URL编码。URL编码只是对%xx对中的原始字节进行编码。由于"®"可以用几种不同的编码方式编码,编码到不同的字节,因此没有一个URL表示。

因此,http://example.com/®不是一个有效的URL,并且没有单一的方法使其有效。您不应该一开始就处理这个URL。