PHP GET请求,发送标头

Jam*_*ery 20 php

我需要执行get请求并随之发送标头.我可以用它做什么?

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

gro*_*gel 42

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

如果您正在使用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);
Run Code Online (Sandbox Code Playgroud)

  • @Purushotamrawat - 是的,如果您按照[此处](/sf/answers/3272098861/)的说明进行操作,为了快速/脏测试,我将其添加到我的“$opts”中:“ssl”=> array('verify_peer'=>false, 'verify_peer_name'=>false)` 并且它有效 (2认同)

amp*_*ine 6

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

为了设置标头(在本例User-Agent中为HTTP请求中的标头),您将使用以下语法:

<?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);
Run Code Online (Sandbox Code Playgroud)