插件窝 干货文章 PHP如何获取http状态码

PHP如何获取http状态码

HTTP status code 获取 932    来源:    2025-03-16

在PHP中,你可以通过多种方式获取HTTP状态码。以下是几种常见的方法:

1. 使用 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;

2. 使用 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;

3. 使用 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;
}

4. 使用 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;
}

5. 使用 http_response_code() 函数

如果你只是想获取当前脚本的HTTP响应状态码,可以使用 http_response_code() 函数。

$status_code = http_response_code();
echo "HTTP Status Code: " . $status_code;

总结

  • 如果你需要获取远程URL的状态码,推荐使用 curlget_headers()
  • 如果你需要获取当前脚本的HTTP响应状态码,可以使用 http_response_code()

根据你的具体需求选择合适的方法。