Mike Sheward Avatar

I’m Mike Sheward, a Web Developer from England, UK.
I enjoy tinkering and engineering things for the Web.

Laravel / PHP - Retrieving and storing remote files

17th May 2017

Copying remote files, or even just reading/parsing the contents of a remote file can be very useful. It can be acheived in just a few lines of PHP too, using the file_get_contents method. This allows us to simply read a files contents and store it as a string, handy!

Next, we check that the retreived file contents are valid, we can do this by using the strict === operator and comparing it to boolean false.

We can use Laravel's handy File Storage put facade to store the contents in a new file, at the moment we are storing this new file locally, however - we may change File Storage driver in the future, using the facade will help us make that an easy transition. If you are not using Laravel, you can use PHP's file_put_contents (see: http://php.net/manual/en/function.file-put-contents.php)

An example function looks like this:

function copyRemoteFile() {

	$fileContents = file_get_contents( 'http://my-remote-site.com/images/cat.jpg' );

	if( $fileContents === false ) {

		// Handle error

	} else {

		$newFilename = 'new-picture-filename.jpg';

		Storage::put( $newFilename, $fileContents );