Home >Backend Development >PHP Tutorial >Examples of POST data using socket, curl, and file_get_contents methods

Examples of POST data using socket, curl, and file_get_contents methods

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:11:05991browse
  1. /**
  2. * Socket version
  3. * How to use:
  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. * Other versions
  47. * How to use:
  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. ?>
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn