我们经常会听人说利用php模拟用户发送post数据,今天出于好奇我找了两个用不同方法来实例post数据的方法,使用 PHP 向页面 POST 数据,代码如下:
- <?php
- 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)<br />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,利用php的socket模拟发送post数据的一个实例,代码如下:
- <?php
- $domain = "127.0.0.1";
- $port = 80;
- $uri = "/ly/post.php";
- $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";
- $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";
- $sock = fsockopen($domain, $port, $errno, $errstr, 30);
- if (!$sock) die("$errstr ($errno)n");
- fputs($sock, $protocolstr);
- $headers = "";
- while ($str = trim(fgets($sock, 4096)))
- $headers .= "$strn";
- $body = "";
- while (!feof($sock))
- $body .= fgets($sock, 4096);
- fclose($sock);
- echo "<h2>Response header:</h2>n";
- echo $headers;
- echo "n";
- echo "<h2>Response body:</h2>n";
- echo $body;
- ?>
在这里我们就不讲关于fsockopen fwrite这些函数的用法了,只讲述模仿过程,有需要的可参考了下. |