【PHP】HTTP 응답 지우기
요점·결론
iconv_mime_decode_headers
라는 신파서explode
, preg_match
에서 샘플 박스
대답의 예는 인터넷의 샘플을 적당히 수집한 것이다.
※ 다음은 LF, HTTP 응답은 CRLF일 수 있으니 적절히 CRLF로 교환해 주십시오.
sample_http_200.txt
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
sample_http_404.txtHTTP/1.1 404 Not Found
Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body>
</html>
PHP
http_parser.php
<?php
/**
* @param string $response
* @return array
* @throws Exception
*/
function parse_http_response(string $response)
{
list($headers, $body) = explode("\r\n\r\n", $response, 2);
if (!preg_match('@HTTP/[0-9\.]+\s+([0-9]+)\s+(.*)\r\n@', $headers, $matches)) {
throw new Exception('status line not found.');
}
$status_code = (int)$matches[1];
$headers = iconv_mime_decode_headers($headers);
return [
'status_code' => $status_code,
'headers' => $headers,
'body' => $body,
];
}
var_dump(parse_http_response(file_get_contents(__DIR__ . '/sample_http_200.txt')));
echo PHP_EOL;
var_dump(parse_http_response(file_get_contents(__DIR__ . '/sample_http_404.txt')));
결실
php http_parser.php
array(3) {
["status_code"]=>
int(200)
["headers"]=>
array(6) {
["Date"]=>
string(29) "Mon, 27 Jul 2009 12:28:53 GMT"
["Server"]=>
string(21) "Apache/2.2.14 (Win32)"
["Last-Modified"]=>
string(29) "Wed, 22 Jul 2009 19:15:56 GMT"
["Content-Length"]=>
string(2) "88"
["Content-Type"]=>
string(9) "text/html"
["Connection"]=>
string(6) "Closed"
}
["body"]=>
string(56) "<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>"
}
array(3) {
["status_code"]=>
int(404)
["headers"]=>
array(5) {
["Date"]=>
string(29) "Sun, 18 Oct 2012 10:36:20 GMT"
["Server"]=>
string(21) "Apache/2.2.14 (Win32)"
["Content-Length"]=>
string(3) "230"
["Connection"]=>
string(6) "Closed"
["Content-Type"]=>
string(29) "text/html; charset=iso-8859-1"
}
["body"]=>
string(224) "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body>
</html>"
}
참고 자료
PHP: iconv_mime_decode_headers - Manual
PHP: preg_match - Manual
HTTP/1.1: Response
Reference
이 문제에 관하여(【PHP】HTTP 응답 지우기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/kumackey/articles/6a04a5c4f9ada2235a33텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)