PHP tip 5: retrieve a remote resource with fopen()

Retrieve a remote resource with fopen()





Sometimes you may need to connect to a REST service to retrieve some data, or simply download a file through a standard HTTP or FTP connection.


The PHP fopen() function is incredibly helpful because it doesn’t just work for local files, but you can also use it to read data from remote locations using different protocols.

In fact, fopen() supports a large number of wrappers, or protocol handlers, that let it connect to local or remote resource through different communication protocols always using the same syntax.


You can use fopen() to get a webpage content and edit it, a common requirement in work environments.

In the following example we change the Google homepage’s title:

/* Remote resource address, with protocol */
$google = '';
/* Open the remote resource */
$resource = fopen($google, 'rb');
/* Get the content as a string */
$content = stream_get_contents($resource);
/* Now we change the HTML title */
$content = str_replace('<title>Google</title>', '<title>My new page</title>', $content);
/* Echo the result (of course we don't have Javascript, CSS etc.) */
echo $content;



You can also use some “shortcut functions” like file() or file_get_contents(), that automatically store the resource data into an array or into a string.

You can see how I use file() to download a remote HTTP file in this Time Handling tutorial.



If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!



Leave a Comment