Sending HTTP requests using cURL in PHP

Date Posted: September 2, 2014, 2:04 am


First things first, in order to use PHP’s cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that’s 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

Basic Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$url = 'http://somewhere.com/link-to-your-api/';
// Define all the required fields needed for your API
$params = array(
    'action'    => 'get_all_user_data',
    'key'       => '456F9DS',
    'user_id'   => '16845',
    'user_email'    => 'data405@gmail.com'
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

// Decode the response
$data = json_decode($response);
print_r($data);

The above code will send an HTTP Request to the given URL and will decode the response then print it to the screen of the requesting client.

If you are dealing with too many HTTP Requests, it would be best to put cURL in a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function cvf_curl_with_response($url, $params ) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ps_response = curl_exec($ch);
    curl_close($ch);
   
    return json_decode($ps_response);
   
}

Then use the function like this:

1
2
3
4
5
6
7
$params = array(
    'action'    => 'get_all_user_data',
    'key'       => '456F9DS',
    'user_id'   => '16845',
    'user_email'    => 'data405@gmail.com'
);
echo cvf_curl_with_response('http://somewhere.com/link-to-your-api/', $params );

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me