三種方法教你如何用PHP模擬post提交資料

meetrice發表於2016-02-16

php模擬post傳值在日常的工作中用到的不是很多,但是在某些特定的場合還是經常用到的。

下面,我整理了三種php模擬post傳值的方法,file_get_contents、curl和socket。
 
第一種:file_get_contents來模擬post
 
  1. <?php
  2.  
  3. function file_get_contents_post($url, $post){
  4.  
  5. $options = array(
  6. 'http'=> array(
  7. 'method'=>'POST',
  8. 'content'=> http_build_query($post),
  9. ),
  10. );
  11.  
  12. $result = file_get_contents($url,false, stream_context_create($options));
  13. return $result;
  14.  
  15. }
  16.  
  17. $data = file_get_contents_post("http://www.a.com/post/post.php", array('name'=>'caiknife','email'=>'caiknife#gmail.com'));
  18. var_dump($data);
 
第二種:curl模擬post
 
  1. <?php
  2.  
  3. function curl_post($url, $post){
  4.  
  5. $options = array(
  6. CURLOPT_RETURNTRANSFER =>true,
  7. CURLOPT_HEADER =>false,
  8. CURLOPT_POST =>true,
  9. CURLOPT_POSTFIELDS => $post,
  10. );
  11.  
  12.  
  13. $ch = curl_init($url);
  14. curl_setopt_array($ch, $options);
  15. $result = curl_exec($ch);
  16. curl_close($ch);
  17. return $result;
  18. }
  19.  
  20. $data = curl_post("http://www.a.com/post/post.php", array('name'=>'caiknife','email'=>'caiknife#gmail.com'));
  21.  
  22. var_dump($data);
 
第三種:socket來模擬post
 
  1. <?php
  2.  
  3. function socket_post($url, $post){
  4. $urls = parse_url($url);
  5. if(!isset($urls['port'])){
  6. $urls['port']=80;
  7. }
  8.  
  9. $fp = fsockopen($urls['host'], $urls['port'], $errno, $errstr);
  10. if(!$fp){
  11. echo "$errno, $errstr";
  12. exit();
  13. }
  14.  
  15. $post = http_build_query($post);
  16. $length = strlen($post);
  17. $header =<<<HEADER
  18.  
  19. <span class="Apple-tab-span" style="white-space:pre"></span>POST {$urls['path']} HTTP/1.1
  20. <span class="Apple-tab-span" style="white-space:pre"></span>Host:{$urls['host']}
  21. <span class="Apple-tab-span" style="white-space:pre"></span>Content-Type: application/x-www-form-urlencoded
  22. <span class="Apple-tab-span" style="white-space:pre"></span>Content-Length:{$length}
  23. <span class="Apple-tab-span" style="white-space:pre"></span>Connection: close
  24. <span class="Apple-tab-span" style="white-space:pre"></span>{$post}
  25. <span class="Apple-tab-span" style="white-space:pre"></span>HEADER;
  26.  
  27. fwrite($fp, $header);
  28. $result ='';
  29. while(!feof($fp)){
  30. $result .= fread($fp,512);
  31. }
  32. $result = explode("\r\n\r\n", $result,2);
  33. return $result[1];
  34.  
  35. }
  36.  
  37. $data = socket_post("http://www.a.com/post/post.php", array('name'=>'caiknife','email'=>'caiknife#gmail.com'));
  38. var_dump($data);
 
上面這三種方法最後看到的內容都是一樣的,都可以得到post的傳值;但是在是用socket的時候,傳送header資訊時必須要注意header的完整資訊,比如content type和content length必須要有,connection: close和post資料之間要空一行,等等;而通過socket取得的內容是包含了header資訊的,要處理一下才能獲得真正的內容。
 
http://www.shuchengxian.com/html/PHP/201512/23.html

相關文章