Backend Development

4 Ways To Make Remote Requests In PHP

Making remote requests is an important aspect of web applications and nowadays most web applications work entirely through remote calls to external Apis. Remote requests is useful when you need to fetch data from external sources like for example the Facebook, Twitter, and Google login that you see in most websites works through remote http calls to external servers and there is many many more of these services.

PHP has alot of ways to make remote requests some of these is limited to simple cases but there are others that can be used to not only fetch data but to send special headers along with the request.

 

1. Using file_get_contents():

with file_get_contents() function you can fetch contents of any file located locally and can be used also to grab contents of external file. file_get_contents() takes the name of the file or url and returns the file contents as a string.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/**
* This is a sample json url
*/
$data = file_get_contents("https://jsonplaceholder.typicode.com/posts");
echo $data;
<?php /** * This is a sample json url */ $data = file_get_contents("https://jsonplaceholder.typicode.com/posts"); echo $data;
<?php
/**
* This is a sample json url
*/
$data = file_get_contents("https://jsonplaceholder.typicode.com/posts");

echo $data;

In the above code we passed file_get_contents() the url of external json webservice and returns the contents as a string.

 

2. Using fopen():

In contrast with file_get_contents() that read the whole file and stores it as string . fopen() can be used to open a file and read it in chunks this is useful in large files that need to be processed line by line. but note here that allow_url_fopen directive must be on for this to work.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$data = "";
if($dataFile = @fopen("http://www.bbc.com", "r" )){
while (!feof($dataFile)) {
$data.= fgets($dataFile, 4096);
}
fclose($dataFile);
}
else{
die("fopen is unable to make remote call check allow_url_fopen is on");
}
echo $data;
<?php $data = ""; if($dataFile = @fopen("http://www.bbc.com", "r" )){ while (!feof($dataFile)) { $data.= fgets($dataFile, 4096); } fclose($dataFile); } else{ die("fopen is unable to make remote call check allow_url_fopen is on"); } echo $data;
<?php

$data = "";

if($dataFile = @fopen("http://www.bbc.com", "r" )){

    while (!feof($dataFile)) {

        $data.= fgets($dataFile, 4096);

    }

    fclose($dataFile);

}
else{
    die("fopen is unable to make remote call check allow_url_fopen is on");
}

echo $data;

As you see in the above we checked if fopen() is able to read the file and then iterate the file contents and read it with fgets() so we supplied the number of characters as the second parameters to fgets() until we read the whole file.

 

3. Using cURL:

The previous two methods of getting data is limited to certain requests but if you need the flexibility in remote calls you should use php cURL.

Before you work with cURL check your phpinfo if cURL is installed and enabled just create a new php file with the following contents:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
echo phpinfo();
<?php echo phpinfo();
<?php
echo phpinfo();

Search for cURL if it is installed then you are ready to go.

cURL allows transfer of data across a wide variety of protocols, and is a very powerful system. It’s widely used as a way to send data across websites, including things like API interaction and oAuth.

The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close()

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/**
* Example GET request
*/
$data = "";
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'
));
// Send the request & save response to $resp
$data = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $data;
<?php /** * Example GET request */ $data = ""; $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts', CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13' )); // Send the request & save response to $resp $data = curl_exec($curl); // Close request to clear up some resources curl_close($curl); echo $data;
<?php
/**
 * Example GET request
 */

$data = "";

$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts',
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'
));
// Send the request & save response to $resp
$data = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

echo $data;

 

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/**
* Example POST request
*/
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'title' => 'title-'.uniqid(),
'body' => 'body-'.uniqid(),
'userId' => 50000
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
<?php /** * Example POST request */ $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts', CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array( 'title' => 'title-'.uniqid(), 'body' => 'body-'.uniqid(), 'userId' => 50000 ) )); // Send the request & save response to $resp $resp = curl_exec($curl); // Close request to clear up some resources curl_close($curl); echo $resp;
<?php
/**
 * Example POST request
 */


$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://jsonplaceholder.typicode.com/posts',
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'title' => 'title-'.uniqid(),
        'body' => 'body-'.uniqid(),
        'userId' => 50000
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

echo $resp;

In the above examples we create two requests the first makes a GET request while the second make a POST request. As you see first we Initialized a curl session with curl_init() then Set various options for the session, then execute and close. there are a lot of options that you can deal with refer to the curl documentation at php.net.

 

4. Using Guzzlephp:

Guzzlephp is another powerful object oriented library built on top of cURL designed for making remote requests and that can make all types of requests including restful calls (GET, POST, PUT, PATCH, DELETE).

Requirements:

  • PHP 5.5.0
  • To use the PHP stream handler, allow_url_fopen must be enabled in your system’s php.ini
  • To use the cURL handler, you must have a recent version of cURL >= 7.19.4 compiled with OpenSSL and zlib.

Installation

you can install guzzlephp with composer as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php composer.phar require guzzlehttp/guzzle:~6.0
php composer.phar require guzzlehttp/guzzle:~6.0
php composer.phar require guzzlehttp/guzzle:~6.0

After installing, you need to require Composer’s autoloader:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
require 'vendor/autoload.php';
require 'vendor/autoload.php';
require 'vendor/autoload.php';

You can send requests with Guzzle using a GuzzleHttp\ClientInterface object.

Creating a Client

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://php.net',
// You can set any number of default request options.
'timeout' => 2.0,
]);
<?php use GuzzleHttp\Client; $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'http://php.net', // You can set any number of default request options. 'timeout' => 2.0, ]);
<?php

use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://php.net',
    // You can set any number of default request options.
    'timeout'  => 2.0,
]);

Clients are immutable in Guzzle 6, which means that you cannot change the defaults used by a client after it’s created.

The client constructor accepts an associative array of options:

base_uri

(string|UriInterface) Base URI of the client that is merged into relative URIs. Can be a string or instance of UriInterface. When a relative URI is provided to a client, the client will combine the base URI with the relative URI using the rules described in RFC 3986, section 2.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
// Send a request to https://foo.com/root
$response = $client->request('GET', '/root');
<?php // Create a client with a base URI $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']); // Send a request to https://foo.com/api/test $response = $client->request('GET', 'test'); // Send a request to https://foo.com/root $response = $client->request('GET', '/root');
<?php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
// Send a request to https://foo.com/root
$response = $client->request('GET', '/root');

 

Sending Requests

Magic methods on the client make it easy to send synchronous requests:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');
<?php $response = $client->get('http://httpbin.org/get'); $response = $client->delete('http://httpbin.org/delete'); $response = $client->head('http://httpbin.org/get'); $response = $client->options('http://httpbin.org/get'); $response = $client->patch('http://httpbin.org/patch'); $response = $client->post('http://httpbin.org/post'); $response = $client->put('http://httpbin.org/put');
<?php
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');

Using Responses

You can get the status code and reason phrase of the response:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
<?php $code = $response->getStatusCode(); // 200 $reason = $response->getReasonPhrase(); // OK
<?php
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

You can retrieve headers from the response:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length');
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
<?php // Check if a header exists. if ($response->hasHeader('Content-Length')) { echo "It exists"; } // Get a header from the response. echo $response->getHeader('Content-Length'); // Get all of the response headers. foreach ($response->getHeaders() as $name => $values) { echo $name . ': ' . implode(', ', $values) . "\r\n"; }
<?php
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
    echo "It exists";
}

// Get a header from the response.
echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
}

The body of a response can be retrieved using the getBody method. The body can be used as a string, cast to a string, or used as a stream like object.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();
<?php $body = $response->getBody(); // Implicitly cast the body to a string and echo it echo $body; // Explicitly cast the body to a string $stringBody = (string) $body; // Read 10 bytes from the body $tenBytes = $body->read(10); // Read the remaining contents of the body as a string $remainingBytes = $body->getContents();
<?php
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();

There are a lot of things you can do with guzzlephp including fetching data and uploading files refer to guzzlephp documentation for full list of options.

5 2 votes
Article Rating

What's your reaction?

Excited
0
Happy
1
Not Sure
1
Confused
0

You may also like

Subscribe
Notify of
guest


0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments