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
)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM