如何在php中获取远程域的HTTP状态代码? [英] How do you get the HTTP status code for a remote domain in php?

查看:76
本文介绍了如何在php中获取远程域的HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个批处理脚本,以遍历数据库中的20,000个链接,并清除所有404等.我如何获取远程URL的HTTP状态代码?

I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url?

最好不使用curl,因为我没有安装它.

Preferably not using curl, since I dont have it installed.

推荐答案

CURL是完美的,但是由于您没有CURL,因此必须使用套接字进行处理.该技术是:

CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is:

  1. 打开服务器的套接字.
  2. 发送HTTP HEAD请求.
  3. 解析响应.

这是一个简单的例子:

<?php

$url = parse_url('http://www.example.com/index.html');

$host = $url['host'];
$port = $url['port'];
$path = $url['path'];
$query = $url['query'];
if(!$port)
    $port = 80;

$request = "HEAD $path?$query HTTP/1.1\r\n"
          ."Host: $host\r\n"
          ."Connection: close\r\n"
          ."\r\n";

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

print "<p>Response: ". $response[1] ."</p>\r\n";

socket_close($socket);

?>

更新:我添加了几行来解析URL

这篇关于如何在php中获取远程域的HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆