PHP GET 请求,发送标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3032643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:28:47  来源:igfitidea点击:

PHP GET Request, sending headers

php

提问by James Jeffery

I need to perform a get request and send headers along with it. What can I use to do this?

我需要执行一个获取请求并随它发送标头。我可以用什么来做到这一点?

The main header I need to set is the browser one. Is there an easy way to do this?

我需要设置的主要标题是浏览器之一。是否有捷径可寻?

回答by grossvogel

If you're using cURL, you can use curl_setopt ($handle, CURLOPT_USERAGENT, 'browser description')to define the user-agent header of the request.

如果您使用 cURL,则可以使用curl_setopt ($handle, CURLOPT_USERAGENT, 'browser description')来定义请求的用户代理标头。

If you're using file_get_contents, check out this tweak of an example on the man page for file_get_contents:

如果您正在使用file_get_contents,请查看file_get_contents手册页上的示例调整:

// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .
              "User-agent: BROWSER-DESCRIPTION-HERE\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);

回答by amphetamachine

If you are requesting a page, use cURL.

如果您要请求页面,请使用cURL

In order to set the headers (in this case, the User-Agentheader in the HTTP request, you would use this syntax:

为了设置标头(在这种情况下,User-AgentHTTP 请求中的标头,您可以使用以下语法:

<?php
$curl_h = curl_init('http://www.example.com/');

curl_setopt($curl_h, CURLOPT_HTTPHEADER,
    array(
        'User-Agent: NoBrowser v0.1 beta',
    )
);

# do not output, but store to variable
curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl_h);

回答by Sarfraz

You can use the headerfunction for that, example:

您可以header为此使用该功能,例如:

header('Location: http://www.example.com?var=some_value');

Note that:

注意:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

请记住,header() 必须在发送任何实际输出之前调用,无论是通过普通的 HTML 标记、文件中的空行还是来自 PHP。使用 include() 或 require() 函数或其他文件访问函数读取代码并且在调用 header() 之前输出空格或空行是一个非常常见的错误。使用单个 PHP/HTML 文件时存在同样的问题。