• socket与模拟http请求


    <?php
    $fp = fsockopen("mingjuli.com",80,$errno,$errstr,5);
    fwrite($fp,"GET /1.txt HTTP/1.1\r\nHost:mingjuli.com\r\nConnection:Close\r\n\r\n");
    ?>

      这段代码可以实现模拟http请求。

      1.fsockopen函数打开socket连接;

      2.fwrite函数把GET请求字符串写入文件指针$fp里,即可请求到1.txt这个文件。(这里的原理是:

      运行-cmd-telnet 192.168.1.234 80(端口80前不要冒号)-GET /1.txt

      按Enter键后就出现了1.txt的内容。

      因为当你在浏览器中输入url回车时,就是在做这个事情,当然浏览器要做的更多。

      整个代码的原理:

      fsocketopen 是直接建立和访问tcp连接的方式,建立后可以用相关协议去访问,比如redis memcache http ftp 等等,输入是用php输出函数实现的fwrite。

      当获取到请求的页面后会自动断开telnet连接是因为:主机在传输完所有的数据后会关闭连接,所以telnet 会显示断开连接。

    利用fsocket模拟GET和POST请求:

    <?php
    // fsocket模拟get提交
    $gurl = "http://localhost/php/t.php?uu=gggggg";
    echo "以下是GET方式的响应内容:<br>";
    sock_get ( $gurl );
    function sock_get($url) {
        $info = parse_url ( $url );
        $fp = fsockopen ( $info ["host"], 80, $errno, $errstr, 3 );
        $head = "GET " . $info ['path'] . "?" . $info ["query"] . " HTTP/1.0\r\n";
        $head .= "Host: " . $info ['host'] . "\r\n";
        $head .= "\r\n";
        $write = fputs ( $fp, $head );
        while ( ! feof ( $fp ) ) {
            $line = fgets ( $fp );
            echo $line . "<br>";
        }
    }
    
    // fsocket模拟post提交
    $purl = "http://localhost/php/t.php";
    echo "以下是POST方式的响应内容:<br>";
    sock_post ( $purl, "uu=rrrrrrrrrrrr&&kk=mmmmmm" );
    function sock_post($url, $query) {
        $info = parse_url ( $url );
        $fp = fsockopen ( $info ["host"], 80, $errno, $errstr, 3 );
        $head = "POST " . $info ['path'] . " HTTP/1.0\r\n";
        $head .= "Host: " . $info ['host'] . "\r\n";
        $head .= "Referer: http://" . $info ['host'] . $info ['path'] . "\r\n";
        $head .= "Content-type: application/x-www-form-urlencoded\r\n";
        $head .= "Content-Length: " . strlen ( trim ( $query ) ) . "\r\n";
        $head .= "\r\n";
        $head .= trim ( $query );
        $write = fputs ( $fp, $head );
        while ( ! feof ( $fp ) ) {
            $line = fgets ( $fp );
            echo $line . "<br>";
        }
    }
    ?>  
    
    <?php
    //请求的响应页面t.php
    if (isset ( $_GET ['uu'] )) {
        echo '<font color="red">t.php中$_GET["uu"]的值是:' . $_GET ['uu'] . "</font><br>";
    }
    if (isset ( $_POST ['uu'] )) {
        echo '<font color="red">t.php中$_POST的值是:</font><br>';
        print_r ( $_POST );
    }
    ?>
  • 相关阅读:
    redis基础配置
    brew安装mysql
    iptables 执行清除命令 iptables -F 要非常小心
    nginx反向代理部署nodejs配置
    Starting MySQL... ERROR! The server quit without updating PID file 问题解决
    iframe自适应高度问题
    js正则常用的一些东西
    node.js批量重命名文件
    [转]MySQL5字符集支持及编码研究
    PHP $_SERVER的使用
  • 原文地址:https://www.cnblogs.com/thinksasa/p/2917519.html
Copyright © 2020-2023  润新知