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

php使用socket、curl、file_get_contents方法POST数据的实例,第1张

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

复制代码

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/473873.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2018-06-01
下一篇 2018-06-01

发表评论

登录后才能评论

评论列表(0条)

保存