file_get_contents: A PHP Alternative to cURL

A comment on my post about cURL mentioned that file_get_contents is a simpler method to use, and in many ways it absolutely is.

file_get_contents is a PHP functions that gets the contents of a file. Unlike cURL it doesn’t require any configuration so you can simply call it as so:

$data = file_get_contents('http://url_to/get_contents/from');

There are some disadvantages, a big one being that some webhosts block the function, but for really quick data retrieval this function is perfect.

Using file_get_contents the example code from my cURL demo would become:

<?php
function bm_getWeather ($code = '', $temp = 'c') {
	$file = 'http://weather.yahooapis.com/forecastrss?p=' . $code . '&u=' . $temp;

	$result = file_get_contents($file);

	$output = array (
		'temperature' => bm_getWeatherProperties('temp', $result),
		'weather' => bm_getWeatherProperties('text', $result),
		'weather_code' => bm_getWeatherProperties('code', $result),
		'class' => 'weatherIcon-' . bm_getWeatherProperties('code', $result),
	);

	return $output;
}

function bm_getWeatherProperties ($needle, $data) {
	$regex = '<yweather .="" :condition.=""></yweather>';
	preg_match($regex, $data, $matches);
	return $matches[1];
}

Note: The weather API I used here is no longer available but the file_get_contents code is still perfectly valid.

Other Alternatives

file_get_contents is great for simple requests but if you need to do anything more complex then the best option is generally cURL. If you’re looking for a cURL alternative then there’s a couple of options:

If you are using WordPress then you can use the WordPress HTTP API to make requests. This is a wrapper for cURL and other methods that makes it easy to make requests and handle the responses.

If you’re not using WordPress then you can use the Guzzle HTTP Client to make requests. This is a PHP library that simplifies the process of loading data from other locations and handles the different responses for you.

Frequently Asked Questions

How do I use file_get_contents to make HTTP requests in PHP?

You can use file_get_contents to make HTTP requests by passing the URL as the argument to the function. It will return the contents of the specified URL as a string.

Can I set custom headers when using file_get_contents to make HTTP requests in PHP?

While file_get_contents itself does not provide a way to set custom headers, you can use the stream_context_create function to create a context with custom headers and pass it as a context option when calling file_get_contents.

What are the advantages of using file_get_contents over cURL in PHP?

file_get_contents is simpler to use for basic HTTP GET requests and does not require installing additional extensions. It’s a good choice for simple scenarios or when cURL is not available.

Are there any limitations or considerations when using file_get_contents for HTTP requests in PHP?

Yes, file_get_contents may not be suitable for handling more complex HTTP scenarios, such as handling different HTTP methods (e.g., POST, PUT) or handling redirects. For those cases, cURL or GuzzleHttp may be more appropriate.

How can I handle errors and exceptions when using file_get_contents for HTTP requests?

You can handle errors by checking the return value of file_get_contents. If it returns false, an error occurred. Additionally, you can use try and catch blocks to handle exceptions that may occur during HTTP requests.

Can I use file_get_contents to download files from the internet in PHP?

Yes, you can use file_get_contents to download files from the internet by specifying the URL of the file you want to download. The function will return the contents of the file as a string. You can then use file_put_contents to save the file to the local filesystem.

What are some common use cases for file_get_contents in PHP beyond making HTTP requests?

Besides making HTTP requests, file_get_contents is often used to read the contents of local files, such as configuration files, JSON files, or XML files.

Is there a way to specify request parameters, such as query parameters, when using file_get_contents for HTTP GET requests in PHP?

Yes, you can append query parameters to the URL when using file_get_contents for HTTP GET requests. Simply include the query parameters in the URL string.

Are there any performance considerations when using file_get_contents for making HTTP requests in PHP?

Performance considerations may include network latency and response times. You can optimize performance by implementing caching mechanisms or using asynchronous techniques for concurrent requests.

What is the substitute for cURL in PHP?

file_get_contents is a common substitute for cURL in PHP when you need to make HTTP requests to retrieve data from a remote server.

Can I use cURL in PHP?

Yes, you can use cURL in PHP to make HTTP requests to remote servers. PHP has a cURL extension that provides functions for this purpose.

Do I have to install cURL in PHP?

To use cURL you may need to install the cURL extension for PHP if it’s not already enabled on your server. You can usually do this using your system’s package manager or by enabling it in your PHP configuration.

Can we use wget instead of curl?

Yes, you can use wget to make HTTP requests in PHP, but it’s less common than using cURL or GuzzleHttp. Using wget should be done using the PHP exec command. cURL and GuzzleHttp offer more flexibility and control when working with HTTP requests.

How do you curl without console output?

To run cURL without console output, you can set the CURLOPT_RETURNTRANSFER option to true using curl_setopt() to capture the response instead of displaying it in the console.

Is Guzzle better than cURL?

Whether Guzzle is better than cURL depends on your specific use case. Guzzle provides a more user-friendly API and is suitable for complex HTTP tasks, while cURL offers lower-level control. Choose the one that fits your project’s requirements.

Let me know what you think on Mastodon, or BlueSky (or Twitter X if you must).

Related Posts

16 Apr 2010

Using cURL to Read the Contents of a Web Page

Recently I wrote about how to use the Yahoo! weather api with WordPress and in the comments I was asked how to use it without relying on WordPress. The answer – is cURL.In this post I’m going to show you...
05 Oct 2021

Randomness with PHP

When I was making my generative art I needed to generate a lot of random things. The simplest way to do that with PHP is to use the rand() function.The rand() function selects a random integer (whole number) between 0...
04 Dec 2012

Disable PHP Short tags

A quick tip for any WordPress devs out there (or any other devs for that matter). Don’t use PHP short tags!I’ve been bitten by this more than once in the past. Some servers allow PHP short tags (<?) and others...
28 May 2010

WordPress caching, Part 2

As I mentioned in WordPress caching part 1, WordPress has built-in caching that can be hooked into by plugins such as W3 Total Cache and Batcache (developed by Andy Skelton who is employed by Automattic).In this article I am going...
20 Apr 2015

Simple PHP Colour Manipulation Functions

The other day I was updating my WordPress plugin, BM Custom Login, and I need some simple colour manipulation functions. In the plugin you can pick colours for different elements of the WordPress login interface, and I wanted to colour...