码迷,mamicode.com
首页 > Web开发 > 详细

php实现请求分流

时间:2018-06-09 14:44:00      阅读:833      评论:0      收藏:0      [点我收藏+]

标签:UNC   .com   amp   create   build   IV   ati   type   get   

一个请求,同时分发到多个服务器,

正常的是: A ============>  B

现在想实现的是:  

                                    --------------> C

        A   ======>  B   ---------------> D

          ---------------> E

如果是 GET请求,就处理一下 URL请求即可,但 POST 请求,还需要处理数据,

处理数据:

    如果是键值对方式的,使用 $_REQUEST 获取整个键值对;

 $post_data = $_REQUEST;   //则会获取 整个请求中的键值对,返回结果为数组;

             如果是以流的方式的,则使用:

$post_data = file_get_contents("php://input");

 

获取完数据后,就用代码来进行转发,需要使用 curl:

** 如果需要根据进来的 url进行判断,可以使用 $_SERVER[‘REQUEST_URI‘]; // 获取的是 url中,domain后的部分,如: https://www.google.com/abc.php  ==>  /abc.php

<?php
    /**
     * 发送post请求,而且data是键值对形式
     */
    function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
                    ‘http‘ => array(
                                    ‘method‘ => ‘POST‘,
                                    ‘header‘ => ‘Content-type:application/x-www-form-urlencoded‘,
                                    ‘content‘ => $postdata,
                                    ‘timeout‘ => 15 * 60
                                )
                    );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }

    /**
     * 发送post请求,而且data是流的形式
     */
    function send_post_content($url, $postdata) {
        $options = array(
                    ‘http‘ => array(
                                    ‘method‘ => ‘POST‘,
                                    ‘header‘ => ‘Content-type:application/x-www-form-urlencoded‘,
                                    ‘content‘ => $postdata,
                                    ‘timeout‘ => 15 * 60
                                )
                    );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }

    // 转发键值对请求 
    if (isset($_REQUEST) && !empty($_REQUEST)) {
        $url1 = "http://test1.php";
        $url2 = "http://test2.php";
        

        $request = $_REQUEST;

        echo send_post($url1, $request);
        /*echo*/ send_post($url2, $request);
    } 
    else {
        // 转发流请求
        $url3 = "http://test3.php";
        $url4 = "http://test4.php";
        

        $request = file_get_contents("php://input"); // $_REQUEST;

        echo send_post_content($url1, $request);
        /*echo*/ send_post_content($url2, $request);
    }

 

php实现请求分流

标签:UNC   .com   amp   create   build   IV   ati   type   get   

原文地址:https://www.cnblogs.com/tommy-huang/p/9159203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!