cszer

php使用fsockopen传送POST到别的URL并取得回应内容

分类: 技术, PHP       评论: 2   阅读:3,610 views

如果不需要传送参数或是使用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
46
47
48
49
50
51
52
//接收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;
}

来自:http://sjolzy.cn/php-fsockopen-sent-using-POST-to-another-URL-and-get-response-to-the-content.html

除非注明,文章皆由( csz )原创,转载请标明本文地址
本文地址: http://www.cszhi.com/20130124/fsockopen-post.html

01-24
2013

发表评论