沃梦达 / 编程问答 / php问题 / 正文

如何从 PHP 发送带有标头的 GET 请求?

How do I send a GET request with a header from PHP?(如何从 PHP 发送带有标头的 GET 请求?)

本文介绍了如何从 PHP 发送带有标头的 GET 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个重复的问题,请告诉我,但这开始变得荒谬了.我想用 PHP:

Call me out if this is a duplicate question, but this is starting to get ridiculous. I want to, with PHP:

 GET http://www.example.com/hello.xyz

并将此标头添加到请求中:

And add this header to the request:

 "X-Header-Name: $foobar" 

其中 foobar 来自已定义的 php 变量.

where foobar comes from a php variable that is already defined.

然后将响应存储在变量中.而已!不多也不少.但是我找不到!我不想使用 curl 或类似的东西,如果我每次都运行 curl,它会减慢速度. 我对使用 curl 的主要担忧是与 Windows 的兼容性(本地服务器)与 Linux(部署服务器).

and then store the response in a variable. That's it! Nothing more, nothing less. But I can't find it! I don't want to use curl or anything like that, it'd slow it down too much if I run curl everytime. My main concern with using curl is about compatibility with Windows (local server) vs. Linux (deployment server).

<?php

echo "So, how do I do it in the simplest way possible?";

?>

推荐答案

您可以使用 file_get_contents 如果你不想使用 curl 但不确定速度,但它是 php 的内置函数,而 curl 不是.在谈论 speed 然后我认为无论您用于远程请求,速度/性能将更多地取决于网络连接速度而不是功能/库,并且它们之间可能有些不同(curl/file_get_contents/fsockopen) 但我认为它会非常少 (1-2 %),而且你看不出区别,它看起来几乎一样.

You may use file_get_contents if you don't want to use curl but not sure about speed but it's php's built in function where curl is not. When talking about speed then I think whatever you use for a remote request, the speed/performance will depend on the network connection speed more than the function/library and maybe there is a bit different among these (curl/file_get_contents/fsockopen) but I think it'll be a very little (1-2 %) and you can't catch the difference, it'll seem almost same.

$opts = array(
  'http'=>array(
      'method'=>"GET",
      'header'=>"X-Header-Name: $foobar"
));
$context = stream_context_create($opts);
$data = file_get_contents('http://www.example.com/hello.xyz', false, $context);
if($data) {
    // do something with data
}

另外,如果你想使用 curl 那么你可以使用这个

Also, if you want to use curl then you may use this

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Header-Name: $foobar"));
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/hello.xyz");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
if ($curl_errno == 0) {
    // $data received in $data
}

另外,检查这个答案,它可能会帮助您做出决定.

Also, check this answer, it may help you to decide.

这篇关于如何从 PHP 发送带有标头的 GET 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从 PHP 发送带有标头的 GET 请求?

基础教程推荐