【问题标题】:how to add a custom request header in php如何在php中添加自定义请求标头
【发布时间】:2015-09-21 11:04:56
【问题描述】:

我想向域发送自定义标头。

我尝试如下:

header("myheader: value1");
//i want to redirect above header to a samplesite now
header('Location: http://localhost/samplesite', FALSE);
exit;

现在在示例站点中,我无法获取我的标题。 如何实现,请帮帮我。

【问题讨论】:

    标签: php http-headers


    【解决方案1】:

    您可以简单地使用 file_get_contents() 发送自定义标头并为其提供上下文。

    看起来像这样:

    $data = http_build_query(array("username" => $uid));
    $opts = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
    
    $context  = stream_context_create($opts);
    $returnedData= file_get_contents("example.com", false, $context);
    

    记住远程主机需要允许这种类型的请求,否则会报错

    您在示例中尝试使用的 header() 函数只会更改从服务器发回的标头,因此 header('Location: http://localhost/samplesite', FALSE); 将只是一个简单的重定向到该站点。

    【讨论】:

      【解决方案2】:

      如果你已经有请求并且需要添加请求头,试试set函数

      $request->headers->set('key', $value);
      

      【讨论】:

        猜你喜欢
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        • 2016-11-14
        • 2012-11-15
        • 2016-03-27
        • 1970-01-01
        相关资源
        最近更新 更多