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:
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!