PHP利用fsockopen POST HTTP请求(URL)并获取返回值

 
  
  1.   $srv_ip = '192.168.1.5';//你的目标服务地址. 
  2.   $srv_port = 80;//端口 
  3.   $url = 'http://localhost/fsock.php'; //接收你post的URL具体地址  
  4.   $fp = ''
  5.   $errno = 0;//错误处理 
  6.   $errstr = '';//错误处理 
  7.   $timeout = 10;//多久没有连上就中断 
  8.   $post_str = "username=demo&password=hahaha";//要提交的内容. 
  9.   //打开网络的 Socket 链接。 
  10.   $fp = fsockopen($srv_ip,$srv_port,$errno,$errstr,$timeout); 
  11.   if (!$fp){ 
  12.    echo('fp fail'); 
  13.   } 
  14.   $content_length = strlen($post_str); 
  15.   $post_header = "POST $url HTTP/1.1\r\n"
  16.   $post_header .= "Content-Type: application/x-www-form-urlencoded\r\n"
  17.   $post_header .= "User-Agent: MSIE\r\n"
  18.   $post_header .= "Host: ".$srv_ip."\r\n"
  19.   $post_header .= "Content-Length: ".$content_length."\r\n"
  20.   $post_header .= "Connection: close\r\n\r\n"
  21.   $post_header .= $post_str."\r\n\r\n"
  22.   fwrite($fp,$post_header); 
  23.  
  24.   $inheader = 1; 
  25.   while(!feof($fp)){//测试文件指针是否到了文件结束的位置 
  26.    $line = fgets($fp,1024); 
  27.    //去掉请求包的头信息 
  28.    if ($inheader && ($line == "\n" || $line == "\r\n")) { 
  29.          $inheader = 0; 
  30.     } 
  31.     if ($inheader == 0) { 
  32.       echo $line
  33.     } 
  34.   } 
  35.   fclose($fp); 
  36.   unset ($line); 
  37. ?> 

 简要说明:代码第二行是你的IP地址或域名,第四行是你要POST的页面的具体地址,本例用的是fsock.php,fsock.php内容如下:

 
  
  1.     echo "username:".$_POST['username']."
    "
  2.     echo "password:".$_POST['password']; 
  3. ?> 

结果为:

username:demo


password:hahaha

你可能感兴趣的:(PHP利用fsockopen POST HTTP请求(URL)并获取返回值)