PHP file_get_contents() 和设置请求标头
2022-08-30 06:53:53
使用PHP,是否可以使用?file_get_contents()
我知道您可以从您的文件中发送用户代理。但是,您能否也发送其他信息,例如 、 和 ?php.ini
HTTP_ACCEPT
HTTP_ACCEPT_LANGUAGE
HTTP_CONNECTION
file_get_contents()
还是有另一个功能可以实现这一点?
使用PHP,是否可以使用?file_get_contents()
我知道您可以从您的文件中发送用户代理。但是,您能否也发送其他信息,例如 、 和 ?php.ini
HTTP_ACCEPT
HTTP_ACCEPT_LANGUAGE
HTTP_CONNECTION
file_get_contents()
还是有另一个功能可以实现这一点?
实际上,在进一步阅读该函数后:file_get_contents()
// Create a stream
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);
你也许能够按照这种模式来实现你所寻求的目标,我还没有亲自测试过这一点。(如果它不起作用,请随时查看我的其他答案)
以下是对我有用的东西(多米尼克只短了一行)。
$url = "";
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n" . // check function.stream-context-create on php.net
"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
)
);
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);