Home  >  Article  >  php教程  >  PHP中使用socket方式GET、POST数据实例教程

PHP中使用socket方式GET、POST数据实例教程

WBOY
WBOYOriginal
2016-06-06 20:05:301438browse

这篇文章主要介绍了PHP中使用socket方式GET、POST数据实例,本文分别给出GET方式和POST方式的代码实例,需要的朋友可以参考下

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

代码如下:

<?php
function socketGet($url, &$ret)
{
 $urlArr = parse_url($url);
 $host = $urlArr[&#39;host&#39;];
 $port = isset($urlArr[&#39;port&#39;])?$urlArr[&#39;port&#39;]:80;
 $path = isset($urlArr[&#39;path&#39;])?$urlArr[&#39;path&#39;]:"/";
 $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;
}
?>

2. 使用 PHP 向页面 POST 数据

代码如下:

<?php
function socketPost($url, $data, &$ret)
{
 $urlArr = parse_url($url);
 $host = $urlArr[&#39;host&#39;];
 $port = isset($urlArr[&#39;port&#39;])?$urlArr[&#39;port&#39;]:80;
 $path = isset($urlArr[&#39;path&#39;])?$urlArr[&#39;path&#39;]:"/";
 $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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn