经常需要判断文件是否可以访问,可以通过http状态码判别,200为正常访问,404为找不到该页面,代码如下:
-
- $url = 'http://www.phpfensi.com';
- function get_http_status_code($url) {
- if(emptyempty($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);
另一种获取http状态码的办法
使用curl需要在php.ini中设置启用才行 >< Windows的服务器中,打开php.ini,找到:
extension=php_curl.dll
去掉前面的注释既可.
PHP实例代码如下:
- $curl = curl_init();
- $url=’http:
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_HEADER, 1);
- curl_setopt($curl,CURLOPT_NOBODY,true);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- $data = curl_exec($curl);
- echo curl_getinfo($curl,CURLINFO_HTTP_CODE);
- curl_close($curl);
|