PHP中使用socket方式GET、POST数据实例
PHP中使用socket方式GET、POST数据实例
发布时间:2016-12-29 来源:查字典编辑
摘要:1.使用PHP获得网页内容GET方式复制代码代码如下:2.使用PHP向页面POST数据复制代码代码如下:如果post报错,把$out.="C...

1. 使用 PHP 获得网页内容 GET方式

复制代码 代码如下:

<?php

function socketGet($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";

return false;

}

else

{

$out = "GET $path HTTP/1.1rn";

$out .= "Host: $hostrn";

$out .= "Connection: Closernrn";

$ret = "";

fwrite($fp, $out);

while (!feof($fp))

{

$ret .= fgets($fp, 128);

}

fclose($fp);

}

return true;

}

?>

2. 使用 PHP 向页面 POST 数据

复制代码 代码如下:

<?php

function socketPost($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";

return false;

}

else

{

$out = "POST $path HTTP/1.1rn";

$out .= "Host: $hostrn";

$out .= "Content-Type: application/x-www-form-urlencodedrn";

$out .= "Content-Length: ".strlen($data)."rn";

$out .= "Connection: Keep-Alivernrn";

$out .= $data;

$ret = "";

fwrite($fp, $out);

while (!feof($fp))

{

$ret .= fgets($fp, 128);

}

fclose($fp);

}

return true;

}

?>

如果post报错,把$out .= "Connection: Keep-Alivernrn";中的Keep-Alive改成Close

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新php教程学习
热门php教程学习
编程开发子分类