簡體   English   中英

PHP和HTTP標頭換行符:用來表示什么字符?

[英]PHP and HTTP Header Line Breaks: What character used to represent?

我遍歷了一系列CURL返回的HTTP標頭的每一行,試圖檢測何時結束以及下一個開始。 我知道http標頭以空行結尾,但是用什么字符來表示php中的此換行符? 我已經嘗試過\\n但是似乎沒有用。 我當然可能做錯了。

用什么字符表示用於終止標題的換行符?

這是我現有的代碼:

$redirect = '';
$regs = '';
foreach ($curl_response as $line)
{   
    if ($line != "\n")
    {   # line is not a linebreak, so we're still processing a header block

        if (preg_match("(HTTP/[0-9]\.[0-9] [0-9]{3} .*)",$line))
        {   # line is the status code
            # highlight the outputted line
            $output .= "<b style='background: yellow;'>$line</b>";
        }

        elseif (preg_match("/^Location: (.*)$/m",$line,$regs)) 
        {   # the line is a location header, so grab the location being redirected to
            # highlight the outputted line
            $output .= "<b style='background: purple; color: white;'>$line</b>";
            $redirect = $regs[1];
        }

        else 
        {   # some other header, record to output
            $output .= $line;
        }

    }

    else 
    {   # we've reached a line break, so we're getting to a new block of redirects
        $output .= "\nreached line break\n";
        if ($redirect != '')
        {   # if we recorded a redirect above, append it to output
            $output .= "\n\nRedirecting to $redirect\n\n";
            $redirect = '';
        }

    }   

}

echo $output;

解決 -原來\\r是我應該匹配的對象。 很奇怪。 不確定是否每個站點都會更改,或者是否設置了卷曲。 到目前為止,其\\r上的所有網站我已經試過。

編輯2 :Doh。 我認為這是因為為了使標頭成一行行,我在\\n上進行了分解。 所以也許任何\\r\\n現在只是\\r ...

$c = explode("\n",$content);

您還需要檢查“ \\ r \\ n”和“ \\ r”,因為它們也是有效的終止空行。

當采用規范形式時,“文本”類型的媒體子類型使用CRLF作為文本換行符。 HTTP放寬了此要求,並允許在整個實體主體上一致執行時僅使用純CR或LF表示換行符的文本媒體傳輸。 HTTP應用程序必須接受CRLF,裸CR和裸LF來表示通過HTTP接收的文本媒體中的換行符。

-HTTP / 1.1:協議參數-3.7.1規范化和文本默認值

標頭以雙換行符結尾,中間沒有空格(即,空行)。 換行符可以是“ \\ n”,“ \\ r \\ n”或只是“ \\ r”。 即使后者不常見,仍需要考慮。

也許您可以找到帶有正則表達式的標頭結尾,例如

list($headers) = preg_split('/(\r\n?|\n)(\r\n?|\n)/', $httpresponse);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM