PHP 模拟POST请求
生活随笔
收集整理的這篇文章主要介紹了
PHP 模拟POST请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 /**
2 * 通過post方式提交表單到指定的url上
3 * @param string host,array data
4 * @return Object
5 */
6 function posttohost($url, $data) {
7 $url = parse_url($url);
8 if (!$url) return "couldn't parse url";
9 if (!isset($url['port'])) { $url['port'] = ""; }
10 if (!isset($url['query'])) { $url['query'] = ""; }
11 $encoded = "";
12 while (list($k,$v) = each($data)) {
13 $encoded .= ($encoded ? "&" : "");
14 $encoded .= rawurlencode($k)."=".rawurlencode($v);
15 }
16 $fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
17 if (!$fp) return "Failed to open socket to $url[host]";
18 fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
19 fputs($fp, "Host: $url[host]\n");
20 fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
21 fputs($fp, "Content-length: " . strlen($encoded) . "\n");
22 fputs($fp, "Connection: close\n\n");
23 fputs($fp, "$encoded\n");
24 $line = fgets($fp,1024);
25 if (!preg_match("/^HTTP\/1\.. 200/i", $line)) return;
26 $results = ""; $inheader = 1;
27 while(!feof($fp)) {
28 $line = fgets($fp,1024);
29 if ($inheader && ($line == "\n" || $line == "\r\n")) {
30 $inheader = 0;
31 }
32 elseif (!$inheader) {
33 $results .= $line;
34 }
35 }
36 fclose($fp);
37 return $results;
38 }
39
40 function curlPost($url,$post_data){
41 $ch = curl_init();
42 curl_setopt($ch, CURLOPT_URL,$url);
43 // curl_setopt($ch, CURLOPT_HEADER, false);
44 // curl_setopt($ch, CURLOPT_TIMEOUT, 5);
45 // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
46 //啟用時會發送一個常規的POST請求,類型為:application/x-www-form-urlencoded,就像表單提交的一樣。
47 curl_setopt($ch, CURLOPT_POST, true);
48 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
49 curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
50 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
51 curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
52 $info= curl_exec($ch);
53 curl_close($ch);
54 return $info;
55
56 }
?
上面一個是使用?fsockopen 和curl進行post提交,我常用的是fsockopen方式。但是PHP的fsockopen、pfsockopen函數會被主機商禁用,只好使用curl模擬POST提交,上面兩個都可以完成POST提交,只是為了防范萬一某一個方法不行,另一個方法或許就是備用的。
附上生成隨機數的方法:
1 /** 2 * 生成隨機驗證碼 3 * @param $length 4 * @return null|string 5 */ 6 function code($length){ 7 $str = null; 8 $strPol = '1234567890ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz'; 9 $max = strlen($strPol)-1; 10 for($i=0;$i<$length;$i++){ 11 $str .= $strPol[rand(0,$max)];//rand($min,$max)生成介于min和max兩個數之間的一個隨機整數 12 } 13 return $str; 14 }?
轉載于:https://www.cnblogs.com/fsong/p/5141162.html
總結
以上是生活随笔為你收集整理的PHP 模拟POST请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网银盾是什么
- 下一篇: 杭州(含嘉兴,绍兴,金华,湖州,义乌)U