简体   繁体   English

在PHP中接收HTTP请求标头

[英]Receiving HTTP Request headers in PHP

I am using cURL for custom HTTP header request. 我将cURL用于自定义HTTP标头请求。 But how can I get PHP to display the headers? 但是如何获取PHP以显示标题?

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('my_key: 12345'));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;
    echo "<br><br>";


    if($_SERVER['my_key']=='12345'){
        echo 'Key is OK';
    } else {
        echo 'Key is wrong';
    }


    // also tried!
    print_r($_COOKIE);
    var_dump (curl_getinfo($ch));

    ?>

I guess easier way for you might be guzzle . 我想对您来说更简单的方法可能是guzzle You just can do something like this: 您可以执行以下操作:

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);

echo $res->getStatusCode();              // "200"
echo $res->getHeader('content-type');    // 'application/json; charset=utf8'
echo $res->getBody();                    // {"type":"User"...' 

More info in docs . 在docs中有更多信息。

In other way, you may check this solution . 以其他方式,您可以检查此解决方案

If you realy want to get your request, but not response headers, you should try this code: 如果您确实希望获取请求,但不想获取响应标头,则应尝试以下代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_getinfo ($ch);
/*[
    "url"                     => "http://www.google.com/",
    "content_type"            => "text/html; charset=UTF-8",
    "http_code"               => 302,
    "header_size"             => 267,
        ...
    "redirect_url"            => "http://www.google.com.ua/?gfe_rd=cr&ei=-fClVYDfA9eEtAH65oGQAQ",
    "request_header"          => "GET / HTTP/1.1\r\nHost: www.google.com\r\nAccept: * /*\r\n\r\n"
]*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM