php 傳送POST到別的URL並取得回應內容 使用fsockopen
php 2009 一月 17th如果不需要傳送參數或是使用GET method傳送
可以直接使用fopen()或是file_get_contents()函式獲得回應內容
但是如果需要不經過表單就送出POST給某URL
就需要使用curl相關函式或是fsockopen()傳送
curl的用法比較簡單
可以咕狗看看(但是php必須要先安裝curl才可以用)
這邊要講的是fsockopen()
//接收POST參數的URL
$url = 'http://www.google.com';
//POST參數,在這個陣列裡,索引是name,值是value,沒有限定組數
$postdata = array('post_name'=>'post_value','acc'=>'hsin','nick'=>'joe');
//函式回覆的值就是取得的內容
$result = sendpost($url,$postdata);
function sendpost($url, $data){
//先解析url 取得的資訊可以看看http://www.php.net/parse_url
$url = parse_url($url);
$url_port = $url['port']==''?(($url['scheme']=='https')?443:80):$url['port'];
if(!$url) return "couldn't parse url";
//對要傳送的POST參數作處理
$encoded = "";
while(list($k,$v)=each($data)){
$encoded .= ($encoded?'&':'');
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
//開啟一個socket
$fp = fsockopen($url['host'],$url_port);
if(!$fp) return "Failed to open socket to ".$url['host'];
//header的資訊
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;
}
二月 25th, 2009 at 20:32:21
[...] 在這篇有提到傳送post的用法 另外說到如果只是要傳送get就可以直接使用fopen或是file_get_contents函式直接取得網頁內容 BUT!!! 這兩天遇到了一個問題 如果因為安全性的關係 要把php.ini中的allow_url_fopen關起來(也就是off) 那就不能使用前述的函式來取得網頁內容 所以只好找另外的方法 也就是使用fsockopen模擬傳送~ (鏘鏘鏘~) [...]