Making a HTTP GET request with HTTP-Basic authentication

后端 未结 4 1010
旧时难觅i
旧时难觅i 2020-12-01 08:01

I need to build a proxy for a Flash Player project I\'m working on. I simply need to make a HTTP GET request with HTTP-Basic authentication to another URL, and serve the res

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 08:32

    I took @clone45's code and turned it into a series of functions somewhat like Python's requests interface (enough for my purposes) using only no external code. Maybe it can help someone else.

    It handles:

    • basic auth
    • headers
    • GET Params

    Usage:

    $url = 'http://sweet-api.com/api';
    $params = array('skip' => 0, 'top' => 5000);
    $header = array('Content-Type' => 'application/json');
    $header = addBasicAuth($header, getenv('USER'), getenv('PASS'));
    $response = request("GET", $url, $header, $params);
    print($response);
    

    Definitions

    function addBasicAuth($header, $username, $password) {
        $header['Authorization'] = 'Basic '.base64_encode("$username:$password");
        return $header;
    }
    
    // method should be "GET", "PUT", etc..
    function request($method, $url, $header, $params) {
        $opts = array(
            'http' => array(
                'method' => $method,
            ),
        );
    
        // serialize the header if needed
        if (!empty($header)) {
            $header_str = '';
            foreach ($header as $key => $value) {
                $header_str .= "$key: $value\r\n";
            }
            $header_str .= "\r\n";
            $opts['http']['header'] = $header_str;
        }
    
        // serialize the params if there are any
        if (!empty($params)) {
            $params_array = array();
            foreach ($params as $key => $value) {
                $params_array[] = "$key=$value";
            }
            $url .= '?'.implode('&', $params_array);
        }
    
        $context = stream_context_create($opts);
        $data = file_get_contents($url, false, $context);
        return $data;
    }
    

提交回复
热议问题