几年前踏上火车那一刻都还没有意识到,从此故乡只有冬夏,再无春秋。
如果不需要傳送參數或是使用GET method傳送
可以直接使用fopen()或是file_get_contents()函式獲得回應內容
但是如果需要不經過表單就送出POST給某URL
就需要使用curl相關函式或是fsockopen()傳送
curl的用法比較簡單
可以咕狗看看(但是php必須要先安裝curl才可以用)
這邊要講的是fsockopen()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| $url = 'http://www.google.com';
$postdata = array('post_name'=>'post_value','acc'=>'hsin','nick'=>'joe');
$result = sendpost($url,$postdata);
function sendpost($url, $data){
$url = parse_url($url); $url_port = $url['port']==''?(($url['scheme']=='https')?443:80):$url['port']; if(!$url) return "couldn't parse url";
$encoded = ""; while(list($k,$v)=each($data)){ $encoded .= ($encoded?'&':''); $encoded .= rawurlencode($k)."=".rawurlencode($v); }
$fp = fsockopen($url['host'],$url_port); if(!$fp) return "Failed to open socket to ".$url['host'];
fputs($fp,'POST '.$url['path'].($url['query']?'?'.$url['query']:'')." HTTP/1.0rn"); fputs($fp,"Host: ".$url['host']."n"); fputs($fp,"Content-type: application/x-www-form-urlencodedn"); fputs($fp,"Content-length: ".strlen($encoded)."n"); fputs($fp,"Connection: closenn"); fputs($fp,$encoded."n");
$line = fgets($fp,1024); if(!eregi("^HTTP/1.. 200", $line)) return; $results = ""; $inheader = 1; while(!feof($fp)){ $line = fgets($fp,2048); if($inheader&&($line == "n" || $line == "rn")){ $inheader = 0; }elseif(!$inheader){ $results .= $line; } } fclose($fp); return $results; }
|
http://inspiregate.com/programming/php/26-php-to-use-fsockopen-to-send-post-to-another-url-and-get-to-respond-to-the-content.html