문제

i have 2 files client.php and server.php. I want to send headers from client to server with curl, and then read this headers in server, but unfortunately I can't get the headers in server file. I tried to do this by using getallheaders() but nothing was displayed. Then I tried get_headers() which says null, when i used var_dump on it.

My client code: ` $result = sendRequest(); echo "res: ".$result;

function sendRequest()
{ 
    $method = 'test';
    $params = array();
    $params["method"] = $method; 
    $post = http_build_query($params, "", "&"); 
    $headers = array(
        "API-Key: test",
        "API-Key2: test2",
        "API-Key3: test3",
        "API-Key4: test4",
    ); 


    $curl = curl_init(); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($curl, CURLOPT_URL, "http://example.com/server.php"); 
    curl_setopt($curl, CURLOPT_POST, true); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 
    //curl_setopt($curl, CURLOPT_HEADER, 1);
    $ret = curl_exec($curl); 

    return $ret; 
}

and the server.php:

get();

function get()
{
    $head = get_headers();
    var_dump($head);
}
도움이 되었습니까?

해결책

Fetches all HTTP request headers from the current request with

apache_request_headers();

look at php.net apache-request-headers

if apache_request_headers() is not available, loop trough the superglobal $_SERVER and get info you need, the request headers starting with HTTP_, like

$headers = array();

foreach ($_SERVER as $key => $value) {
    if (preg_match('/^HTTP_.+/', $key)) {
        // sanitize keys removing HTTP_
        $headers[str_replace('HTTP_','',$key)] = $value;
    }
}

to use

echo $headers['API-Key'];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top