我們經常會聽人說利用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這些函數的用法了,只講述模仿過程,有需要的可參考了下.
新聞熱點
疑難解答