首页 > 开发 > PHP > 正文

php模拟用户发送post数据方法

2024-05-04 21:58:19
字体:大 中 小
来源:转载
供稿:网友

我们经常会听人说利用php模拟用户发送post数据,今天出于好奇我找了两个用不同方法来实例post数据的方法,使用 PHP 向页面 POST 数据,代码如下:

  1. <?php 
  2. function socketPost($url, $data, &$ret) 
  3. { 
  4.  $urlArr = parse_url($url); 
  5.  $host = $urlArr['host']; 
  6.  $port = isset($urlArr['port'])?$urlArr['port']:80; 
  7.  $path = isset($urlArr['path'])?$urlArr['path']:"/"; 
  8.  $fp = fsockopen($host, $port, $errno, $errstr, 30); 
  9.  if (!$fp) 
  10.  { 
  11.      echo "$errstr ($errno)<br />n"; 
  12.   return false; 
  13.  } 
  14.  else 
  15.  { 
  16.      $out = "POST $path HTTP/1.1rn"; 
  17.      $out .= "Host: $hostrn"; 
  18.   $out .= "Content-Type: application/x-www-form-urlencodedrn"; 
  19.   $out .= "Content-Length: ".strlen($data)."rn"; 
  20.      $out .= "Connection: Keep-Alivernrn"; 
  21.   $out .= $data; 
  22.   $ret = ""; 
  23.      fwrite($fp, $out); 
  24.      while (!feof($fp)) 
  25.   { 
  26.          $ret .= fgets($fp, 128); 
  27.      } 
  28.      fclose($fp); 
  29.  } 
  30.  return true; 
  31. } 
  32. ?> 

如果post报错,把$out .= "Connection: Keep-Alivernrn";中的Keep-Alive改成Close,利用php的socket模拟发送post数据的一个实例,代码如下:

  1. <?php    
  2. $domain = "127.0.0.1";    
  3. $port = 80;    
  4. $uri = "/ly/post.php";    
  5. $data="txtName=111&txtEmail=222@1.net&rabSex=%D0%A1%BD%E3&txtFrom=%BD%AD%CE%F7%C1%FA%C4%CF&txtQq=2222&txtUrl=33333333&txtFace=images%2Fface%2Fface05.gif&txtEm=images%2Fem%2Fem01.gif&txtBody=rrr";    
  6. $protocolstr ="POST {$uri} HTTP/1.1rnHost: {$domain}rnContent-type: application/x-www-form-urlencodedrnContent-length: " . strlen($data) . "rnReferer: http://10.10.10.10/ly/index.phprnUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)rnAccept: */*rnrn{$data}rnrn";  
  7. $sock = fsockopen($domain, $port, $errno, $errstr, 30);    
  8. if (!$sock) die("$errstr ($errno)n");    
  9. fputs($sock, $protocolstr);  
  10. $headers = "";    
  11. while ($str = trim(fgets($sock, 4096)))    
  12.   $headers .= "$strn";  
  13. $body = "";    
  14. while (!feof($sock))    
  15.   $body .= fgets($sock, 4096);    
  16. fclose($sock);  
  17. echo "<h2>Response header:</h2>n";    
  18. echo $headers;    
  19. echo "n";  
  20. echo "<h2>Response body:</h2>n";    
  21. echo $body;    
  22. ?>    

在这里我们就不讲关于fsockopen fwrite这些函数的用法了,只讲述模仿过程,有需要的可参考了下.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表