php開啟其他網站獲取狀態碼

2020-07-16 10:06:45

php開啟其他網站獲取狀態碼?

php獲取http狀態碼程式程式碼

經常需要判斷檔案是否可以存取,可以通過http狀態碼判別,200為正常存取,404為找不到該頁面,程式碼如下

<?php
// 設定url
$url = 'http://www.111cn.net';
function get_http_status_code($url) {
 if(empty($url)) return false;
 $url = parse_url($url);
 $host = isset($url['host']) ? $url['host'] : '';
 $port = isset($url['port']) ? $url['port'] : '80';
 $path = isset($url['path']) ? $url['path'] : '';
 $query = isset($url['query']) ? $url['query'] : '';
 $request = "HEAD $path?$query HTTP/1.1rn"
           ."Host: $hostrn"
           ."Connection: closern"
           ."rn";
 $address = gethostbyname($host);
 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 socket_connect($socket, $address, $port);
 socket_write($socket, $request, strlen($request));
 $response = split(' ', socket_read($socket, 1024));
 socket_close($socket);
 return  trim($response[1]);
}
echo get_http_status_code($url);

以上就是php開啟其他網站獲取狀態碼的詳細內容,更多請關注TW511.COM其它相關文章!