php fsockopen函数发送post,get请求获得网页内容,反防采集

  1. $post =1;
  2. $url = parse_url($url);
  3. $host ='http://www.phpfensi.com';
  4. $path ='/';
  5. $query ='?action=phpfensi.com';
  6. $port =80;
  7. if($post) {
  8. $out = "post $path http/1.0 ";
  9. $out .= "accept: */* ";
  10. //$out .= "referer: $boardurl ";
  11. $out .= "accept-language: zh-cn ";
  12. $out .= "content-type: application/x-www-form-urlencoded ";
  13. $out .= "user-agent: $_server[http_user_agent] ";
  14. $out .= "host: $host ";
  15. $out .= 'content-length: '.strlen($post)." ";
  16. $out .= "connection: close ";
  17. $out .= "cache-control: no-cache ";
  18. $out .= "cookie: $cookie ";
  19. $out .= $post;
  20. } else {
  21. $out = "get $path http/1.0 ";
  22. $out .= "accept: */* ";
  23. //$out .= "referer: $boardurl ";
  24. $out .= "accept-language: zh-cn ";
  25. $out .= "user-agent: $_server[http_user_agent] ";
  26. $out .= "host: $host ";
  27. $out .= "connection: close ";
  28. $out .= "cookie: $cookie ";
  29. }
  30. $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
  31. if(!$fp)
  32. {
  33. return '';//note $errstr : $errno
  34. } else {
  35. return '成功访问';
  36. }

fsockopen语法:resource fsockopen(string $hostname [,int $port = -1 [, int &$errno [,string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

启动一个套接字连接到指定的主机的资源,php支持在互联网领域的目标和unix在所支持的套接字传输列表说明,所支持的传输列表也可以检索使用stream_get_transports().

该插座预设会被启用,阻塞模式,你可以切换到非阻塞模式使用stream_set_blocking(),如果上面实例看不懂,就来看个简的吧,代码如下:

  1. $fp = fsockopen("www.phpfensi.com", 80, $errno, $errstr, 30);
  2. if (!$fp) {
  3. echo "$errstr ($errno)

    " >;

  4. } else {
  5. $out = "get / http/1.1 ";
  6. $out .= "host: www.phpfensi.com";
  7. $out .= "connection: close ";
  8. fwrite($fp, $out);
  9. while (!feof($fp)) {
  10. echo fgets($fp, 128);
  11. }
  12. fclose($fp);
  13. }