简体   繁体   English

PHP GET请求,发送标头

[英]PHP GET Request, sending headers

I need to perform a get request and send headers along with it. 我需要执行一个get请求,并发送标头。 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? 是否有捷径可寻?

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);

If you are requesting a page, use cURL . 如果要请求页面,请使用cURL

In order to set the headers (in this case, the User-Agent header in the HTTP request, you would use this syntax: 为了设置标头(在这种情况下,HTTP请求中的User-Agent标头),您可以使用以下语法:

<?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);

You can use the header function 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. 请记住,必须先通过常规HTML标记,文件中的空白行或从PHP发送任何实际输出,然后调用header()。 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. 使用include()或require(),函数或另一个文件访问函数读取代码,并在调用header()之前输出空格或空行,这是一个非常常见的错误。 The same problem exists when using a single PHP/HTML file. 使用单个PHP / HTML文件时,存在相同的问题。

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

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