Home > Article > Backend Development > Detailed explanation of fsockopen imitating post and get in php_PHP tutorial
In php, the fsockopen function can imitate users to visit some websites and can also bring some commonly used information, such as browser, IP, post, get and other data. I will introduce them to you one by one below.
If you want to use the fsockopen function, we must set allow_url_fopen = On in php.ini.
Example
fsockopen() Example
The code is as follows | Copy code | ||||||||
if (!$fp) { echo "$errstr ($errno) n"; } else { $out = "GET / HTTP/1.1rn";
|
Code As follows | Copy code | tr>
< ?php <🎜><🎜> $srv_ip = '192.168.1.5';//Your target service address. <🎜><🎜> $srv_port = 80;//Port <🎜><🎜> $url = 'http ://localhost/fsock.php'; //The specific URL to receive your post <🎜><🎜> $fp = ''; <🎜><🎜> $errno = 0;//Error handling <🎜>< 🎜> $errstr = '';//Error handling <🎜><🎜> $timeout = 10;//How long it will take before the connection is interrupted <🎜><🎜> $post_str = "username=demo&password=hahaha";// Content to be submitted. <🎜><🎜> //Open the network Socket link. <🎜><🎜> $fp = fsockopen($srv_ip,$srv_port,$errno,$errstr,$timeout); <🎜><🎜> if (!$fp){ <🎜><🎜> echo('fp fail'); <🎜><🎜> } <🎜><🎜> $content_length = strlen($post_str); <🎜><🎜> $post_header = "POST $url HTTP/1.1rn"; <🎜><🎜 > $post_header .= "Content-Type: application/x-www-form-urlencodedrn"; <🎜><🎜> $post_header .= "User-Agent: MSIErn"; <🎜><🎜> $post_header .= " Host: ".$srv_ip."rn"; <🎜><🎜> $post_header .= "Content-Length: ".$content_length."rn"; <🎜><🎜> $post_header .= "Connection: closernrn" ; <🎜><🎜> $post_header .= $post_str."rnrn"; <🎜><🎜> fwrite($fp,$post_header); <🎜><🎜> <🎜><🎜> $inheader = 1; <🎜><🎜> while(!feof($fp)){//Test whether the file pointer reaches the end of the file <🎜><🎜> $line = fgets($fp,1024); <🎜><🎜> //Remove the header information of the request packet <🎜><🎜> if ($inheader && ($line == "n" || $line == "rn")) { <🎜><🎜> $inheader = 0; <🎜><🎜> } <🎜><🎜> if ($inheader == 0) { <🎜><🎜> echo $line; <🎜><🎜> } <🎜><🎜> } <🎜>< 🎜> fclose($fp); <🎜><🎜> unset ($line); <🎜><🎜>?> |
Brief description: The second line of the code is your IP address or domain name, and the fourth line is the specific address of the page you want to POST. This example uses fsock.php. The content of fsock.php is as follows:
代码如下 | 复制代码 |
echo "username:".$_POST['username']." echo "password:".$_POST['password']; ?>
|
echo "username:".$_POST['username']."
";
echo "password:".$_POST ['password'];
代码如下 | 复制代码 |
//fsocket模拟post提交 |
username: demo