简体   繁体   English

如何在 PHP 中发出 HTTP 请求?

[英]How to make an HTTP request in PHP?

I have to send an SMS by making an HTTP request via GET method.我必须通过 GET 方法发出 HTTP 请求来发送 SMS。 The link contains information in the form of GET variables, eg该链接包含 GET 变量形式的信息,例如

http://www.somelink.com/file.php?from=12345&to=67890&message=hello%20there

After I run the script it has to be as if someone clicked the link and activated the SMS sending process.在我运行脚本之后,就好像有人单击了链接并激活了 SMS 发送过程一样。

I have found some links about get request and curl and what not, it's all so confusing!我发现了一些关于 get request 和 curl 的链接,什么不是,这一切都太令人困惑了!

I think the easiest way to make an HTTP request via GET method from PHP is using file_get_contents() .我认为通过 PHP 的 GET 方法发出 HTTP 请求的最简单方法是使用file_get_contents()

<?php
$response = file_get_contents('http://example.com/send-sms?from=12345&to=67890&message=hello%20there');
echo $response;

Don't forget to see the notes section for info on PHP configuration required for this to work.不要忘记查看注释部分以获取有关此工作所需的 PHP 配置的信息。 You need to set allow_url_fopen to true in your php.ini .您需要在php.ini中将allow_url_fopen设置为 true 。

Note that this works for GET requests only and that you will have no access to the headers (request, nor response).请注意,这仅适用于 GET 请求,您将无法访问标头(请求或响应)。 Also, enabling allow_url_fopen might not be a good choice for security reasons.此外,出于安全原因,启用allow_url_fopen可能不是一个好的选择。

The easiest way is probably to use cURL.最简单的方法可能是使用 cURL。 See https://web.archive.org/web/20180819060003/http://codular.com/curl-with-php for some examples.有关一些示例,请参见https://web.archive.org/web/20180819060003/http://codular.com/curl-with-php

Lets assume that we want to retrive http://www.google.com假设我们要检索http://www.google.com

$cURL = curl_init();
$setopt_array = array(CURLOPT_URL => "http://www.google.com",    CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array()); 
curl_setopt_array($cURL, $setopt_array);
$json_response_data = curl_exec($cURL);
print_r($json_response_data);
curl_close($cURL);

/* cURL is preinstalled by goDaddy.com and many other php hosting providers it is also preinstalled in wamp and xampp good luck. /* cURL 由 goDaddy.com 和许多其他 php 托管服务提供商预装,它也预装在 wamp 和 xampp 中,祝你好运。 */ */

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

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