php uses fsockopen function to send post and get requests to obtain web page content

  • 2021-08-03 09:48:37
  • OfStack

This paper describes the method of php using fsockopen function to send post, get request to obtain web page content. Share it for your reference.

The specific implementation code is as follows:

$post =1; 
$url = parse_url($url);
$host ='https://www.ofstack.com';
$path ='/';
$query ='?action=phpfensi.com';
$port =80;
 
if($post) {
  $out = "post $path http/1.0 ";
  $out .= "accept: */* ";
  //$out .= "referer: $boardurl ";
  $out .= "accept-language: zh-cn ";
  $out .= "content-type: application/x-www-form-urlencoded ";
  $out .= "user-agent: $_server[http_user_agent] ";
  $out .= "host: $host ";
  $out .= 'content-length: '.strlen($post)." ";
  $out .= "connection: close ";
  $out .= "cache-control: no-cache ";
  $out .= "cookie: $cookie ";
  $out .= $post;
 } else {
  $out = "get $path http/1.0 ";
  $out .= "accept: */* ";
  //$out .= "referer: $boardurl ";
  $out .= "accept-language: zh-cn ";
  $out .= "user-agent: $_server[http_user_agent] ";
  $out .= "host: $host ";
  $out .= "connection: close ";
  $out .= "cookie: $cookie ";
 }
 $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
 if(!$fp) 
 {
  return '';//note $errstr : $errno 
 } else {
  return ' Successful access ';
 }

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

Start a socket to connect to the specified host resource, php supports the target in the Internet domain and unix describes the supported socket transport list, and the supported transport list can also be retrieved using stream_get_transports ().

The socket will be enabled by default, blocking mode, you can switch to non-blocking mode and use stream_set_blocking (). If you don't understand the above example, let's look at a simple one. The code is as follows:

$fp = fsockopen("www.ofstack.com", 80, $errno, $errstr, 30); 
 if (!$fp) {
  echo "$errstr ($errno) ";
 } else {
  $out = "get / http/1.1 ";
  $out .= "host: www.ofstack.com";
  $out .= "connection: close ";
  fwrite($fp, $out);
  while (!feof($fp)) {
   echo fgets($fp, 128);
  }
  fclose($fp);
 }

I hope this article is helpful to everyone's PHP programming.


Related articles: