《PHP编程:PHP中使用socket方式GET、POST数据实例》要点:
本文介绍了PHP编程:PHP中使用socket方式GET、POST数据实例,希望对您有用。如果有疑问,可以联系我们。
PHP编程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.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);
}
return true;
}
?>
PHP编程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.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);
}
return true;
}
?>
假如post报错,把$out .= "Connection: Keep-Alive\r\n\r\n";中的Keep-Alive改成Close
欢迎参与《PHP编程:PHP中使用socket方式GET、POST数据实例》讨论,分享您的想法,维易PHP学院为您提供专业教程。
转载请注明本页网址:
http://www.vephp.com/jiaocheng/11143.html