>  기사  >  백엔드 개발  >  PHP中使用socket方式GET、POST数据实例_php实例

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

WBOY
WBOY원래의
2016-06-07 17:13:36688검색

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

复制代码 代码如下:

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)
\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 数据

复制代码 代码如下:

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)
\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
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.