Home >Backend Development >PHP Tutorial >Use PHP to implement GET and POST data_PHP tutorial

Use PHP to implement GET and POST data_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:49:45912browse

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.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 数据
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.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 

摘自  与时俱进

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478311.htmlTechArticle1. 使用 PHP 获得网页内容 GET方式 ?php function socketGet($url, $ret) { $urlArr = parse_url($url); $host = $urlArr[host]; $port = isset($urlArr[port])?$urlArr[port]:80; $pa...
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