当前位置:Gxlcms > PHP教程 > php使用socket、curl、file_get_contents方法POST数据的实例

php使用socket、curl、file_get_contents方法POST数据的实例

时间:2021-07-01 10:21:17 帮助过:15人阅读

  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.0\r\n");
  11. fwrite($socket,"User-Agent: Socket Example\r\n");
  12. fwrite($socket,"HOST: $remote_server\r\n");
  13. fwrite($socket,"Content-type: application/x-www-form-urlencoded\r\n");
  14. fwrite($socket,"Content-length: ".strlen($post_string)+8."\r\n");
  15. fwrite($socket,"Accept:*/*\r\n");
  16. fwrite($socket,"\r\n");
  17. fwrite($socket,"mypost=$post_string\r\n");
  18. fwrite($socket,"\r\n");
  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'."\r\n".
  56. 'User-Agent : Jimmy\'s POST Example beta'."\r\n".
  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. ?>

人气教程排行