php下获取http状态的实现代码

  在项目开发中,有时我们需要知道远程的URL地址是否能访问正常,判断其正常与否后进行下一步的操作,那么在PHP中如何获取远程HTTP的状态呢?

  文件preg.php

header("HTTP/1.1 404 Not Found");

  方式一、

$url = "http://www.demo.com/preg.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $httpCode;
curl_close($ch);

  运行结果:

404

  方式二、

echo '<pre>';
print_r(get_headers("http://www.demo.com/preg.php",1));

  运行结果:

Array
(
    [0] => HTTP/1.1 404 Not Found
    [Date] => Fri, 28 Sep 2018 09:27:03 GMT
    [Server] => Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.5.38
    [X-Powered-By] => PHP/5.5.38
    [Content-Length] => 0
    [Content-Type] => text/html
)
posted @ 2018-09-28 17:26  周国伟  阅读(1984)  评论(0编辑  收藏  举报