zoukankan      html  css  js  c++  java
  • PHP fsockopen模拟POST/GET方法

    原文链接:http://www.nowamagic.net/academy/detail/12220214

    fsockopen 除了前面小节的模拟生成 HTTP 连接之外,还能实现很多功能,比如模拟 post 和 get 传送数据的方法。比如下面的例子:

    //fsocket模拟post提交
    $url = "http://localhost/test2.php?site=nowamagic.net";
    print_r(parse_url($url));
    
    //echo $query;
    sock_get($url,"user=gonn");
    //sock_get($url, $query);
    
    //fsocket模拟get提交
    function sock_get($url, $query)
    {
        $data = array(
        'foo'=>'bar', 
        'baz'=>'boom', 
        'site'=>'www.nowamagic.net', 
        'name'=>'nowa magic'); 
        
        $query_str = http_build_query($data);
        
        $info = parse_url($url);
        $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
        //$head = "GET ".$info['path']."?".$info["query"]." HTTP/1.0
    ";
        $head = "GET ".$info['path']."?".$query_str." HTTP/1.0
    ";
        $head .= "Host: ".$info['host']."
    ";
        $head .= "
    ";
        $write = fputs($fp, $head);
        while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }
    }
    
    sock_post($url,"user=gonn");
    
    function sock_post($url, $query)
    {    
        $info = parse_url($url);
        $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
        $head = "POST ".$info['path']."?".$info["query"]." HTTP/1.0
    ";
        $head .= "Host: ".$info['host']."
    ";
        $head .= "Referer: http://".$info['host'].$info['path']."
    ";
        $head .= "Content-type: application/x-www-form-urlencoded
    ";
        $head .= "Content-Length: ".strlen(trim($query))."
    ";
        $head .= "
    ";
        $head .= trim($query);
        $write = fputs($fp, $head);
        while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }
    }

    接收页面 test2.php 的代码为:

    $data = $_REQUEST;
    
    echo '<pre>';
    print_r( $data );
    echo '</pre>';
  • 相关阅读:
    标签的讲解
    属性分类
    LeetCode 003. 无重复字符的最长子串 双指针
    Leetcode 136. 只出现一次的数字 异或性质
    Leetcode 231. 2的幂 数学
    LeetCode 21. 合并两个有序链表
    象棋博弈资源
    acwing 343. 排序 topsort floyd 传播闭包
    Leetcode 945 使数组唯一的最小增量 贪心
    Leetcode 785 判断二分图 BFS 二分染色
  • 原文地址:https://www.cnblogs.com/zakun/p/5981119.html
Copyright © 2011-2022 走看看