首頁 >後端開發 >php教程 >php使用socket、curl、file_get_contents方法POST資料的實例

php使用socket、curl、file_get_contents方法POST資料的實例

WBOY
WBOY原創
2016-07-25 09:11:05950瀏覽
  1. /**
  2. * Socket版本
  3. * 使用方法:
  4. * $post_string = "app=socket&version=beta";
  5. * request_by_socket('www.1bo8.cn','/restServer.php',$post_string);
  6. */
  7. function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){
  8. $socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout);
  9. if (!$socket) die("$errstr($errno)");
  10. fwrite($socket,"POST $remote_path HTTP/1.0rn");
  11. fwrite($socket,"User-Agent: Socket Examplern");
  12. fwrite($socket,"HOST: $remote_serverrn");
  13. fwrite($socket,"Content-type: application/x-www-form-urlencodedrn");
  14. fwrite($socket,"Content-length: ".strlen($post_string)+8."rn");
  15. fwrite($socket,"Accept:*/*rn");
  16. fwrite($socket,"rn");
  17. fwrite($socket,"mypost=$post_stringrn");
  18. fwrite($socket,"rn");
  19. $header = "";
  20. while ($str = trim(fgets($socket,4096))) {
  21. $header.=$str;
  22. }
  23. $data = "";
  24. while (!feof($socket)) {
  25. $data .= fgets($socket,4096);
  26. }
  27. return $data;
  28. }
  29. /**
  30. * Curl版本
  31. * 使用方法:
  32. * $post_string = "app=request&version=beta";
  33. * request_by_curl('http://www.1bo8.cn/restServer.php',$post_string);
  34. */
  35. function request_by_curl($remote_server,$post_string){
  36. $ch = curl_init();
  37. curl_setopt($ch,CURLOPT_URL,$remote_server);
  38. curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string);
  39. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  40. curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta");
  41. $data = curl_exec($ch);
  42. curl_close($ch);
  43. return $data;
  44. }
  45. /**
  46. * 其它版本
  47. * 使用方法:
  48. * $post_string = "app=request&version=beta";
  49. * request_by_other('http://www.1bo8.cn/restServer.php',$post_string);
  50. */
  51. function request_by_other($remote_server,$post_string){
  52. $context = array(
  53. 'http'=>array(
  54. 'method'=>'POST',
  55. 'header'=>'Content-type: application/x-www-form-urlencoded'."rn".
  56. 'User-Agent : Jimmy's POST Example beta'."rn".
  57. 'Content-length: '.strlen($post_string)+8,
  58. 'content'=>'mypost='.$post_string)
  59. );
  60. $stream_context = stream_context_create($context);
  61. $data = file_get_contents($remote_server,FALSE,$stream_context);
  62. return $data;
  63. }
  64. ?>
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn