一个使用socket来抓取数据的例子

本博客展示了如何通过POST请求将评论发送到指定网站的新闻页面,并使用多种编程方式实现这一操作,包括直接使用socket和stream_socket_client函数。同时,通过file_get_contents函数的配置来模拟POST请求,实现远程内容的抓取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$post_ =array (
	'author' => 'Gonn',
	'mail'=>'gonn@nowamagic.net',
	'url'=>'http://www.nowamagic.net/',
	'text'=>'欢迎访问简明现代魔法');

$data=http_build_query($post_);
$fp = fsockopen("nowamagic.net", 80, $errno, $errstr, 5);

$out="POST http://nowamagic.net/news/1/comment HTTP/1.1\r\n";
$out.="Host: typecho.org\r\n";
$out.="User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"."\r\n";
$out.="Content-type: application/x-www-form-urlencoded\r\n";
$out.="PHPSESSID=082b0cc33cc7e6df1f87502c456c3eb0\r\n";
$out.="Content-Length: " . strlen($data) . "\r\n";
$out.="Connection: close\r\n\r\n";
$out.=$data."\r\n\r\n";

fwrite($fp, $out);
while (!feof($fp))
{
    echo fgets($fp, 1280);
}

fclose($fp);

我们也可以用stream_socket 实现,这很简单,只需要打开socket的代码换成下面的即可:
$fp = stream_socket_client("tcp://nowamagic.net:80", $errno, $errstr, 3);

再来看一个stream的例子:

file_get_contents函数一般常用来读取文件内容,但这个函数也可以用来抓取远程url,起到和curl类似的作用。

$opts = array (
	'http'=>array(
	   'method' => 'POST',
	   'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .
				  "Content-Length: " . strlen($data) . "\r\n",
	   'content' => $data)
);

$context = stream_context_create($opts);
file_get_contents('http://nowamagic.net/news/1/comment', false, $context);

注意第三个参数,$context,即HTTP流上下文,可以理解为套在file_get_contents函数上的一根管道。同理,我们还可以创建FTP流,socket流,并把其套在对应的函数在。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值