PHP利用Curl、socket、file_get_contents POST数据

 1 /** 
 2 * 其它版本 
 3 * 使用方法: 
 4 * $post_string = "app=request&version=beta"; 
 5 * request_by_other('http://facebook.cn/restServer.php',$post_string); 
 6 */ 
 7 function request_by_other($remote_server,$post_string){ 
 8     $context = array( 
 9         'http'=>array( 
10             'method'=>'POST', 
11             'header'=>'Content-type: application/x-www-form-urlencoded'."\r\n". 
12                       'User-Agent : Jimmy\'s POST Example beta'."\r\n". 
13                       'Content-length: '.strlen($post_string)+8, 
14             'content'=>.$post_string) 
15          ); 
16     $stream_context = stream_context_create($context); 
17     $data = file_get_contents($remote_server,FALSE,$stream_context); 
18      return $data; 
19 }
20 
21  
22 
23 /** 
24 * Socket版本 
25 * 使用方法: 
26 * $post_string = "app=socket&version=beta"; 
27 * request_by_socket('facebook.cn','/restServer.php',$post_string); 
28 */ 
29 function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){ 
30     $socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout); 
31      if (!$socket) die("$errstr($errno)"); 
32     
33     fwrite($socket,"POST $remote_path HTTP/1.0\r\n"); 
34     fwrite($socket,"User-Agent: Socket Example\r\n"); 
35     fwrite($socket,"HOST: $remote_server\r\n"); 
36     fwrite($socket,"Content-type: application/x-www-form-urlencoded\r\n"); 
37     fwrite($socket,"Content-length: ".strlen($post_string)+8."\r\n"); 
38     fwrite($socket,"Accept:*/*\r\n"); 
39     fwrite($socket,"\r\n"); 
40     fwrite($socket,"mypost=$post_string\r\n"); 
41     fwrite($socket,"\r\n"); 
42     
43     $header = ""; 
44      while ($str = trim(fgets($socket,4096))) { 
45         $header.=$str; 
46      } 
47     
48     $data = ""; 
49      while (!feof($socket)) { 
50         $data .= fgets($socket,4096); 
51      } 
52     
53      return $data; 
54 }
55 
56 /** 
57 * Curl版本 
58 * 使用方法: 
59 * $post_string = "app=request&version=beta"; 
60 * request_by_curl('http://facebook.cn/restServer.php',$post_string); 
61 */ 
62 function request_by_curl($remote_server,$post_string){ 
63     $ch = curl_init(); 
64     curl_setopt($ch,CURLOPT_URL,$remote_server); 
65     curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string); 
66     curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
67     curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta"); 
68     $data = curl_exec($ch); 
69     curl_close($ch); 
70      return $data; 
71 }
posted @ 2011-03-23 12:55  无天暗帝  阅读(387)  评论(0)    收藏  举报