一、用file_get_contents来模拟post

  1. <?php  
  2. function file_get_contents_post($url$post) {  
  3.     $options = array(  
  4.         ‘http’ => array(  
  5.             ‘method’ => ‘POST’,  
  6.             // ‘content’ => ‘name=caiknife&email=caiknife@gmail.com’,  
  7.             ‘content’ => http_build_query($post),  
  8.         ),  
  9.     );  
  10.   
  11.     $result = file_get_contents($url, false, stream_context_create($options));  
  12.   
  13.     return $result;  
  14. }  
  15.   
  16. $data = file_get_contents_post(“https://www.a.com/post/post.php”array(‘name’=>‘caiknife’’email’=>‘caiknife@gmail.com’));  
  17.   
  18. var_dump($data);  

二、用curl来模拟post

  1. <?php  
  2. function curl_post($url$post) {  
  3.     $options = array(  
  4.         CURLOPT_RETURNTRANSFER => true,  
  5.         CURLOPT_HEADER         => false,  
  6.         CURLOPT_POST           => true,  
  7.         CURLOPT_POSTFIELDS     => $post,  
  8.     );  
  9.   
  10.     $ch = curl_init($url);  
  11.     curl_setopt_array($ch$options);  
  12.     $result = curl_exec($ch);  
  13.     curl_close($ch);  
  14.     return $result;  
  15. }  
  16.   
  17. $data = curl_post(“https://www.a.com/post/post.php”array(‘name’=>‘caiknife’’email’=>‘caiknife@gmail.com’));  
  18.   
  19. var_dump($data);  

三、用socket来模拟post:

  1. <?php  
  2. function socket_post($url$post) {  
  3.     $urls = parse_url($url);  
  4.     if (!isset($urls[‘port’])) {  
  5.         $urls[‘port’] = 80;  
  6.     }  
  7.   
  8.     $fp = fsockopen($urls[‘host’], $urls[‘port’], $errno$errstr);  
  9.     if (!$fp) {  
  10.         echo “$errno, $errstr”;  
  11.         exit();  
  12.     }  
  13.   
  14.     $post = http_build_query($post);  
  15.     $length = strlen($post);  
  16.     $header = <<<HEADER  
  17. POST {$urls[‘path’]} HTTP/1.1  
  18. Host: {$urls[‘host’]}  
  19. Content-Type: application/x-www-form-urlencoded  
  20. Content-Length: {$length}  
  21. Connection: close  
  22.   
  23. {$post}  
  24. HEADER;  
  25.   
  26.     fwrite($fp$header);  
  27.     $result = ;  
  28.     while (!feof($fp)) {  
  29.         // receive the results of the request  
  30.         $result .= fread($fp, 512);  
  31.     }  
  32.     $result = explode(“rnrn”$result, 2);  
  33.     return $result[1];  
  34. }  
  35.   
  36. $data = socket_post(“https://www.a.com/post/post.php”array(‘name’=>‘caiknife’’email’=>‘caiknife@gmail.com’));  
  37.   
  38. var_dump($data);  

这三种方法最后看到的内容都是一样的,但是在是用socket的时候,发送header信息时必须要注意header的完整信息,比如content type和content length必须要有,connection: close和post数据之间要空一行,等等;而通过socket取得的内容是包含了header信息的,要处理一下才能获得真正的内容。