使用带有参数的 file_get_contents 从 PHP 获取请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7352832/
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-26 02:32:45  来源:igfitidea点击:

GET Request from PHP using file_get_contents with parameters

phphttpgetfile-get-contents

提问by Hormigas

I want to send a GET request to an external site, but also want to send some parameters

我想向外部站点发送 GET 请求,但也想发送一些参数

for example i've to send a get request to example.com

例如,我必须向 example.com 发送获取请求

i want to execute www.example.com/send.php?uid=1&pwd=2&msg=3&phone=3&provider=xyz

我想执行 www.example.com/send.php?uid=1&pwd=2&msg=3&phone=3&provider=xyz

My code is :

我的代码是:

$getdata = http_build_query(
array(
    'uid' => '1',
    'pwd' => '2',
 'msg'=>'3',
 'phone'=>'9999',
 'provider'=>'xyz'
 )
);

$opts = array('http' =>
 array(
    'method'  => 'GET',
    'content' => $getdata
)
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/send.php', false, $context);

I get a server error .

我收到服务器错误。

回答by webbiedave

The contentoption is used with POSTand PUTrequests. For GETyou can just append it as a query string:

content选项与POSTPUT请求一起使用。因为GET您可以将其附加为查询字符串:

file_get_contents('http://example.com/send.php?'.$getdata, false, $context);

Furthermore, the methoddefaults to GETso you don't even need to set options, nor create a stream context. So, for this particular situation, you could simply call file_get_contentswith the first parameter if you wish.

此外,method默认设置为GET因此您甚至不需要设置选项,也不需要创建流上下文。因此,对于这种特殊情况,您可以根据需要简单地file_get_contents使用第一个参数进行调用。