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

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

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

 
 
  1. <?php 
  2.     echo "username:".$_POST['username']."<br/>"
  3.     echo "password:".$_POST['password']; 
  4. ?> 

结果为:

username:demo


password:hahaha

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值