在PHP中,你可以通过多种方式获取HTTP状态码。以下是几种常见的方法:
get_headers()
函数get_headers()
函数可以获取一个URL的所有HTTP头信息,包括状态码。
$url = 'http://example.com';
$headers = get_headers($url, 1);
// 获取状态码
$status_line = $headers[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status_code = $match[1];
echo "HTTP Status Code: " . $status_code;
curl
扩展curl
是一个强大的工具,可以用来发送HTTP请求并获取响应信息,包括状态码。
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "HTTP Status Code: " . $status_code;
file_get_contents()
和 $http_response_header
file_get_contents()
函数可以用来获取URL的内容,同时可以通过 $http_response_header
变量获取HTTP头信息。
$url = 'http://example.com';
$content = file_get_contents($url);
if ($content === FALSE) {
echo "Failed to retrieve content.";
} else {
// 获取状态码
preg_match('{HTTP\/\S*\s(\d{3})}', $http_response_header[0], $match);
$status_code = $match[1];
echo "HTTP Status Code: " . $status_code;
}
stream_context_create()
和 file_get_contents()
你可以使用 stream_context_create()
创建一个上下文,然后通过 file_get_contents()
获取内容并检查状态码。
$url = 'http://example.com';
$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$content = file_get_contents($url, false, $context);
if ($content === FALSE) {
echo "Failed to retrieve content.";
} else {
// 获取状态码
preg_match('{HTTP\/\S*\s(\d{3})}', $http_response_header[0], $match);
$status_code = $match[1];
echo "HTTP Status Code: " . $status_code;
}
http_response_code()
函数如果你只是想获取当前脚本的HTTP响应状态码,可以使用 http_response_code()
函数。
$status_code = http_response_code();
echo "HTTP Status Code: " . $status_code;
curl
或 get_headers()
。http_response_code()
。根据你的具体需求选择合适的方法。