Calling an external API using a server [duplicate] - php

I have to send an SMS by making an HTTP request via GET method. The link contains information in the form of GET variables, e.g.
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.
I have found some links about get request and curl and what not, it’s all so confusing!

I think the easiest way to make an HTTP request via GET method from PHP is using 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. You need to set allow_url_fopen to true in your php.ini.
Note that this works for GET requests only and that you will have no access to the headers (request, nor response). Also, enabling allow_url_fopen might not be a good choice for security reasons.

The easiest way is probably to use cURL. See https://web.archive.org/web/20180819060003/http://codular.com/curl-with-php for some examples.

Lets assume that we want to retrive 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.
*/

Related

How can I Connect to other server

I want to make a platform to get disk space usage of several server.
How i can do it?
$df = disk_free_space("/");
i want this line of code to be executed on my all servers
It's not easy or maybe impossible with only php, the best solution in my opinion is send a request with curl to the server that return the disk space usage.
One way is to use the ssh2_XXX functions of PHP to login to each server and run df /.
Another way is to create a web page on each server that runs disk_free_space('/') and echoes the result. Then you can use file_get_contents("http://servername/disk_free.php") to query each server.
on each server, you can insert a page that returns the free space:
http://server1.com/GetFreeSpace.php
http://server2.com/GetFreeSpace.php
http://server3.com/GetFreeSpace.php
GetFreeSpace.php
<?php
echo disk_free_space("/");
You can use cURL to query several servers
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://server1.com/GetFreeSpace.php',
CURLOPT_RETURNTRANSFER => true
));
echo curl_exec($ch);
There are many ways to do this. Curl is an option, you can use cron on each server, that runs at specific time and updates the value to a web server, or you can use ssh to get the same info.

PHP SEND SMS API

have a look at below snippet inside my PHP code :
function SMS(){
$msg1="".$bookingNo."\n".$guestName."\n".$guestEmail."\n".$guestPhone."\n".$guestAddress."\n".$place."\n".$account."\n".$reportingDate."\n".$reportingTime."";
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
The problem is this that this http link is sending SMS successfully when run on browser window,
with some dummy text in &message=.
But when I am assigning all defined and tested variables inside $msg1 & calling it in same url.
Woosh, it shows NO ERROR & nothing happens, on calling this function. NO SMS.
I wonder where m wrong ?
Thanks
UPDATED CODE :
function SMS(){
$bookingNo=$_REQUEST['bookingNo'];
$guestName=$_REQUEST['guestName'];
$guestEmail=$_REQUEST['guestEmail'];
$guestPhone=$_REQUEST['guestPhone'];
$guestAddress=$_REQUEST['guestAddress'];
$place=$_REQUEST['place'];
$account=$_REQUEST['account'];
$reportingDate=$_REQUEST['reportingDate'];
$reportingTime=$_REQUEST['reportingTime'];
$msg1="".$bookingNo."\n".$guestName."\n".$guestEmail."\n".$guestPhone."\n".$guestAddress."\n".$place."\n".$account."\n".$reportingDate."\n".$reportingTime."";
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
}
SMStoDriver();
Newline characters are not allowed in URLs. You need to encode the message:
function SMS(){
$bookingNo=$_REQUEST['bookingNo'];
$guestName=$_REQUEST['guestName'];
$guestEmail=$_REQUEST['guestEmail'];
$guestPhone=$_REQUEST['guestPhone'];
$guestAddress=$_REQUEST['guestAddress'];
$place=$_REQUEST['place'];
$account=$_REQUEST['account'];
$reportingDate=$_REQUEST['reportingDate'];
$reportingTime=$_REQUEST['reportingTime'];
$msg1=urlencode("Booking No: $bookingNo\nName: $guestName\n Email: $guestEmail\nPhone: $guestPhone\nAddress: $guestAddress\nPlace: $place\nAccount: $account\nDate: $reportingDate\nTime: $reportingTime");
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
}
It looks like you are trying to use the file method to make the web request. Perhaps your PHP ini is configured to not allow file I/O requests to URLs.
You would be better off making the web request with something like cURL.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message=test',
));
$resp = curl_exec($curl);
curl_close($curl);

Calling function or script on another server and receiving response

What I essentially want to do is to be able to call a function or script on another server using PHP and receive a response. Let me set up an example:
On my web application, I have a page, and I need to send some data to the server, have the server do some work and then return a response.
Web application:
<?php
// call server script, sending it for example a string, "testString", then wait for a response
?>
Server script:
<?php
// get the string "testString", so some work on it and return it, displaying it on the web app
?>
I'm not looking for someone to complete this for me, just to head me in the right direction. I've read that cURL can be useful for this, but have yet to be able to get any examples to work for me, such as these ones:
http://www.jonasjohn.de/snippets/php/curl-example.htm
How to get response using cURL in PHP
So what's an ideal route to head in to solve my problem?
cURL operates just like a browser basically. It makes an HTTP request to a server and gets back the response. So one server is the 'client' and one server is the 'server'.
On the server server (lol), set up a page called index.php that outputs some text
<?php
echo 'hello from the server server';
Then from the client server, create a page called index.php to make the cURL request to the server server.
<?php
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.serverserver.com', <--- edit that URL
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
var_dump($result);
Then, when you go to the client server URL, the client server will hit the server server, just like it was a person using a browser over HTTP, and print the result to the screen.
Hope that helps. Didn't actually test it.
If you do not have control over both the machines or the host server does not provide you with an API to be able to do that, this is not doable. Otherwise it is as simple as setting up some code on host server which will receive commands from your client, then process and respond accordingly. Once that is setup then you can easily call your server code with either cURL or even file_get_contents

How to add a parameter to the request header sent by a PHP script?

I'm trying to use a web service REST API for which I need to add a parameter for authorization (with the appropriate key, of course) to get a XML result. I'm developing in PHP. How can I add a parameter to the request header in such a situation?
Edit: The way I'm doing the request right now is $xml = simplexml_load_file($query_string);
Are you using curl? (recommended)
I assume that you are using curl to do these requests towards the REST API, if you aren't; use it.
When using curl you can add a custom header by calling curl_setopt with the appropriate parameters, such as in below.
curl_setopt (
$curl_handle, CURLOPT_HTTPHEADER,
array ('Authentication-Key: foobar')
); // make curl send a HTTP header named 'Authentication-key'
// with the value 'foobar'
Documentation:
PHP: cURL - Manual
PHP: curl_setopt - Manual
Are you using file_get_contents or similar?
This method is not recommended, though it is functional.
Note: allow_url_fopen needs to be enabled for file_get_contents to be able to access resources over HTTP.
If you'd like to add a custom header to such request you'll need to create yourself a valid stream context, as in the below snippet:
$context_options = array(
'http' =>array (
'method' => 'GET',
'header' => 'Authentication-Key'
)
);
$context = stream_context_create ($context_options);
$response = file_get_contents (
'http://www.stackoverflow.com', false, $context_options
);
Documentation:
PHP: file_get_contents - Manual
PHP: stream_context_create - Manual
PHP: Runtime Configuration, allow_url_fopen
I'm using neither of the above solutions, what should I do?
[Post OP EDIT]
My recommendation is to fetch the data using curl and then pass it off to the parser in question when all the data is received. Separate data fetching from the processing of the returned data.
[/Post OP EDIT]
When you use $xml = simplexml_load_file($query_string);, the PHP interpreter invokes it's wrapper over fopen to open the contents of a file located at $query_string. If $query_string is a remote file, the PHP interpreter opens a stream to that remote URL and retrieves the contents of the file there (if the HTTP response code 200 OK). It uses the default stream context to do that.
There is a way to alter the headers sent by altering that stream context, however, in most cases, this is a bad idea. You're relying on PHP to always open all files, local or remote, using a function that was meant to take a local file name only. Not only is it a security problem but it also could be the source of a bug that is very hard to track down.
Instead, consider splitting the loading of the remote content using cURL (checking the returned HTTP status code and other sanity checks) and then parsing that content into a SimpleXMLElement object to use. When you use cURL, you can set any headers you want to send with the request by invoking something similar to curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName' => 'value');
Hope this helps.

How to send a GET request from PHP?

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
Unless you need more than just the contents of the file, you could use file_get_contents.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
$response = http_get("http://www.example.com/file.xml");
Remember that if you are using a proxy you need to do a little trick in your php code:
(PROXY WITHOUT AUTENTICATION EXAMPLE)
<?php
$aContext = array(
'http' => array(
'proxy' => 'proxy:8080',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
?>
Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');
echo $response->getStatusCode();
echo $response->getBody();
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part
I like using fsockopen open for this.
On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages.
Actually, REST API is a way to use services from a site.
So, there are many PHP packages developed to simplify REST API call. For example here is a very nice one:
https://github.com/romanpitak/PHP-REST-Client
Using such packages helps you to fetch resources easily.
So, getting the xml file (that you mentioned about) is as easy as:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Categories