How curl url in php?

Today, we’re going to explore the cURL extension in PHP, which allows you to make HTTP requests from your code.

Often you need to communicate with external websites in your day-to-day PHP development. Whether it’s calling third-party REST APIs to fetch data or downloading resources from an external website, you want a library which allows you to do it effortlessly.

In PHP, there are different methods you can use to connect and communicate with different types of servers. One of the easiest ways is to use the file_get_contents function to read remote files. On the other hand, you can also use sockets to implement client-server communication. In this article, though, we’re going to discuss the cURL extension in detail, with real-world examples.

cURL stands for client URLs, and it’s a library which allows you to send and receive information with the URL syntax. In fact, it leverages the libcurl library, created by Daniel Stenberg, which allows you to connect to and communicate with many different types of servers with many different types of protocols. Apart from HTTP and HTTPS, the libcurl library also supports protocols like FTP, Gopher, Telnet, DICT, File, and LDAP.

From the next section onwards, we'll go through a couple of real-world examples to demonstrate how you can use cURL functions in PHP.

Real-World Examples

In this section, we’ll build real-world examples to demonstrate various cURL functions in PHP.

How to Download Files Using cURL in PHP

Reading or downloading remote files is one of the most common use cases for cURL. This is accomplished by a cURL GET request, which we’ll discuss in this section.

Go ahead and create the curl_read_file.php file with the following contents.

In the above example, we’ve used cURL functions to read the home page of the example.com domain. Let’s go through the important snippets to understand how it works.

Firstly, we’ve used the curl_init function to initialize a new cURL session. The $curlHandle variable holds a cURL handle, which we can use to set various options for cURL transfer with the help of the curl_setopt function.

When you’re working with cURL, the curl_setopt function is the one you will mostly deal with, since it allows you to initialize various CURLOPT_* request options. The curl_setopt function takes three arguments: a cURL handle, the CURLOPT_XXX option, and the value of the CURLOPT_XXX option.

Next, we’ve used the CURLOPT_URL option to set the request URL to example.com with the curl_setopt function. Further, we’ve set the CURLOPT_RETURNTRANSFER option to TRUE as we want to initialize the response into the $responseData variable. If we don’t set it to TRUE, the response will be displayed directly on the screen. Lastly, we’ve set the CURLOPT_HEADER option to FALSE to skip the header information in the output.

Finally, we’ve used the curl_exec function to execute the cURL request. If everything goes fine, the $responseData variable should contain the source of the home page of example.com.

How to Post Data Using cURL in PHP

In this section, we’ll see how to post data with cURL.

Let’s create the curl_post_example.php file with the following contents.

 'Value 1',
    'field_name_2' => 'Value 2',
    'field_name_3' => 'Value 3'
);

$fields_string = http_build_query($fields);

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);

$data = curl_exec($curl);

curl_close($curl);

In the above example, we assume that we need to submit a request with the HTTP POST method. In fact, it works similarly to submitting a form with the POST method.

The $fields variable holds an array of values that we need to submit as POST data. Next, we’ve used the http_build_query function to prepare a URL-encoded query string.

Next, we’ve set the CURLOPT_POST option to TRUE to set the request method to HTTP POST. Further, we need to use the CURLOPT_POSTFIELDS option to set the POST data that we want to submit along with the request.

Finally, we’ve used the curl_exec function to execute the cURL request. So in this way, you can make a cURL POST request.

How to Post JSON Data Using cURL in PHP

More often than not, you need to submit JSON data in a cURL POST request. In this section, we’ll see how you can submit JSON data with the POST method in a cURL request.

Since it’s a POST request, let’s revise the example which we’ve just discussed in the previous section. Go ahead and create the curl_post_json.php file with the following contents.

 'Value 1',
    'field_name_2' => 'Value 2',
    'field_name_3' => 'Value 3'
);

$json_string = json_encode($fields);

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );

$data = curl_exec($curl);

curl_close($curl);

Although it may look similar to the example in the previous section, the important thing is that we’ve used the json_encode function to create a JSON string from the $fields array.

Next, we’ve used the CURLOPT_HTTPHEADER option to set the Content-Type header to application/json to inform the API server that we’re sending JSON data. The Content-Type header is useful to post data in different formats. For example, if you wanted to send XML data, you would have to set the Content-Type header to application/xml.

Except for that, it’s pretty much the same as that of the regular POST request. So in this way, you can post different types of data by setting the appropriate Content-Type header. If you don't set the Content-Type header, it will use application/x-www-form-urlencoded as the default value.

How to Upload Files Using cURL in PHP

In this section, we’ll discuss how you can upload files with cURL.

Let’s create the curl_post_file.php file with the following contents.

 'Value 1',
    'field_name_2' => 'Value 2',
    'field_name_3' => 'Value 3',
    'uploaded_file' => $fileAttachment
);

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);

$data = curl_exec($curl);

curl_close($curl);

When you want to upload a file, you need to create a CURLFile object in the first place. As of PHP 5.5+, it’s fairly easy to create it, as you just need to use the curl_file_create function to create a CURLFile object. The first argument of the curl_file_create function is the absolute path of the file which you want to upload.

If you are still using an older PHP version, which is not recommended, we’ve used the fallback '@' . realpath('/absolute/path/to/file/') syntax to create a file link.

Finally, we’ve set the Content-Type header to multipart/form-data as it’s going to be a multipart form POST request. Apart from that, it’s a routine cURL POST request.

So far, we've gone through a couple of different cURL methods that are frequently used in PHP. In the next section, we’ll see how you can use the Guzzle library, which makes things easier for you when you’re dealing with HTTP requests in PHP.

What Is the Guzzle HTTP Client?

As per the official documentation:

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

Let’s quickly go through the benefits of using Guzzle over the cURL PHP functions:

  • a simple interface for different types of data
  • supports both synchronous and asynchronous requests
  • supports cURL, sockets, and PHP streams
  • PSR-7 compliant
  • and more

All in all, it’s one of the best libraries to use when you want to make HTTP calls with different methods. In this section, we’ll discuss how to install Guzzle, followed up by a couple of quick examples to demonstrate the power of this library!

How to Install the Guzzle Library

The official documentation recommends that you use Composer to install Guzzle. Let’s run the following command to install Guzzle in your project.

$composer require guzzlehttp/guzzle:^7.0
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing psr/http-client (1.0.1): Loading from cache
  - Installing ralouphie/getallheaders (3.0.3): Loading from cache
  - Installing guzzlehttp/psr7 (1.7.0): Loading from cache
  - Installing guzzlehttp/promises (1.4.1): Loading from cache
  - Installing guzzlehttp/guzzle (7.2.0): Loading from cache
guzzlehttp/psr7 suggests installing laminas/laminas-httphandlerrunner (Emit PSR-7 responses)
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
Writing lock file
Generating autoload files

Once it’s installed, you need to require Composer's autoloader, as shown in the following snippet.

require 'vendor/autoload.php';

And with that, you’re ready to use Guzzle!

How to Make a GET Request With Guzzle

In this section, we’ll see how you can send GET requests with Guzzle.

We’ll revise the example which we discussed earlier, as it will help you to understand how you could convert your existing cURL PHP code to a Guzzle-based implementation.

Let’s have a look at the revised example.

get('https://example.com');

$responseContents = $response->getBody();

Isn’t it straightforward? We’ve created an instance of the \GuzzleHttp\Client class, and it’s assigned to the $client variable. And now, you have access to plenty of utility methods provided by the \GuzzleHttp\Client class.

In our case, we need to fetch content with the GET method, so we’ve used the get method of the \GuzzleHttp\Client class, and it will return the GuzzleHttp\Psr7\Response object. The GuzzleHttp\Psr7\Response object provides various methods like getStatusCode, getBody, getReasonPhrase, and more. We’ve used the getBody method to fetch the response body contents.

So that’s how you can perform HTTP GET requests with Guzzle.

How to Make a POST Request With Guzzle

In this section, we’ll see how you can perform HTTP POST requests with Guzzle.

We’ll revise the curl_post_example.php example, which we discussed in the earlier section. The revised code with Guzzle looks like this.

 [
        "field_name_1" => "Value 1",
        "field_name_2" => "Value 2",
        "field_name_3" => "Value 3",
    ]
];

$response = $client->post("{POST_REST_ENDPOINT}", $options);
$responseContents = $response->getBody();
?>

Since this is a POST request, we need to pass the $options array as the second argument of the post method. In our example, it contains the form data that we need to submit as POST data.

If you’re wondering how to post JSON data, you just need to change the form_params key to json, and the data will be sent as JSON!

Also, if you want to send any HTTP headers along with a request, you can do it with the headers key, as shown in the following snippet.

...
...
$headers = array(
    'Content-Type'   => 'application/json'
);
$options = [
    'form_params' => [
            "field_name_1" => "Value 1",
            "field_name_2" => "Value 2",
            "field_name_3" => "Value 3",
    ],
    ‘headers’ => $headers
];
...
...

In fact, the Guzzle library provides a lot of configuration options for every method. Also, there are multiple ways to do the same thing, so I encourage you to explore it in detail, and I’m sure it will be fun!

So that was a quick introduction to the Guzzle library, along with the PHP cURL functions.

Conclusion

Today, we explored the basics of the cURL extension in PHP. We discussed how you can perform different types of HTTP requests with cURL in PHP. Also, we went through a quick introduction to the Guzzle library, which makes life easier for developers when dealing with HTTP requests in PHP.

Did you find this post useful?

How curl url in php?

Software Engineer, FSPL, India

I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

How get cURL URL in PHP?

The Way to Download the Contents of a Remote Website to a Local File Using cURL in PHP. $url_name = "https://google.com"; $ch_session = curl_init(); curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1);

How does PHP handle cURL request?

php. $url = "https://www.javatpoint.com/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);.
// create cURL resource..
$ch = curl_init() ;.
//set cURL options..
//Run cURL (execute http request).
$res = curl_exec($ch) ;.
// close cURL resource..

What are the cURL options in PHP?

Available since PHP 7.3. 0 and libcurl >= cURL 7.52. ... Parameters ¶.

What is curl_exec?

curl_exec(CurlHandle $handle ): string|bool. Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.