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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短