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

WBOY
Libérer: 2016-07-25 09:11:05
original
926 Les gens l'ont consulté
  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. ?>
复制代码


source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal