PHP中使用socket方式GET、POST数据实例
1.使用PHP获得网页内容GET方式
<?php
functionsocketGet($url,&$ret)
{
$urlArr=parse_url($url);
$host=$urlArr['host'];
$port=isset($urlArr['port'])?$urlArr['port']:80;
$path=isset($urlArr['path'])?$urlArr['path']:"/";
$fp=fsockopen($host,$port,$errno,$errstr,30);
if(!$fp)
{
echo"$errstr($errno)<br/>\n";
returnfalse;
}
else
{
$out="GET$pathHTTP/1.1\r\n";
$out.="Host:$host\r\n";
$out.="Connection:Close\r\n\r\n";
$ret="";
fwrite($fp,$out);
while(!feof($fp))
{
$ret.=fgets($fp,128);
}
fclose($fp);
}
returntrue;
}
?>
2.使用PHP向页面POST数据
<?php
functionsocketPost($url,$data,&$ret)
{
$urlArr=parse_url($url);
$host=$urlArr['host'];
$port=isset($urlArr['port'])?$urlArr['port']:80;
$path=isset($urlArr['path'])?$urlArr['path']:"/";
$fp=fsockopen($host,$port,$errno,$errstr,30);
if(!$fp)
{
echo"$errstr($errno)<br/>\n";
returnfalse;
}
else
{
$out="POST$pathHTTP/1.1\r\n";
$out.="Host:$host\r\n";
$out.="Content-Type:application/x-www-form-urlencoded\r\n";
$out.="Content-Length:".strlen($data)."\r\n";
$out.="Connection:Keep-Alive\r\n\r\n";
$out.=$data;
$ret="";
fwrite($fp,$out);
while(!feof($fp))
{
$ret.=fgets($fp,128);
}
fclose($fp);
}
returntrue;
}
?>
如果post报错,把$out.="Connection:Keep-Alive\r\n\r\n";中的Keep-Alive改成Close
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下