php下獲取http狀態的實現代碼

  在項目開發中,有時咱們須要知道遠程的URL地址是否能訪問正常,判斷其正常與否後進行下一步的操做,那麼在PHP中如何獲取遠程HTTP的狀態呢?php

  文件preg.phphtml

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

  方式1、curl

$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);

  運行結果:url

404

  方式2、htm

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

  運行結果:blog

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
)
相關文章
相關標籤/搜索