Jun
24
2014

Download Files with PHP (From a List)

Ever have one of those days where you get a new codebase on your desk, but realize that you’re missing ALL THE IMAGES?  (face slap).

I’ve had plenty of those, and here’s how to stop slapping yourself and just use PHP to download files from a list in a text file!

The Directory Structure

Easy enough, but just to be safe, the following is the directory structure used for this:

process.php
attachment.txt
files/

Process.php

The bare bones of process.php does only 2 things:

  1. Opens a text file
  2. Loops through the contents and downloads each file

This can be done in 6 lines of code (for reference, I always refer to lines of code that include line breaks), but to beef it up a bit and provide some feedback so we know how many files were downloaded, and how many were unable to be downloaded.

We’re going to start by adding 2 counters (always starting at 0), and open the text file as an array using PHP’s “file()” function…

//Start a couple of counters
$c = 0;
$e = 0;

//Open the file as an array
$file = file( 'attachment.txt' );

Now assuming the file ‘attachment.txt’ HAS contents, we’ll continue- but be advised if the file is empty, the following foreach loop will throw an error.

//Loop through the file contents. This assumes the file HAS contents.
foreach( $file as $dl )
{
    //Trim the URL of any excess whitespace
    $url = trim( $dl );
    //Line up a path for the file to go locally
    $img = './files/' . basename( trim( $dl ) );
    //Try to move the file
    $put = file_put_contents( $img, file_get_contents( $url ) );
    //Success, add to the counter
    if( $put )
    {
        $c++;
    }
    //Fail, add to the counter and let the user know which file failed
    else
    {
        echo "<p><strong>Unable to download: " . $dl . "</strong></p>";
        $e++;
    }
}

And if you’d like to get ‘super crafty’, you can add the following to the bottom, which will tell the user how many files were downloaded, and how many failed:

//Last success output
echo "<h2>Successfully downloaded " . $c . " images</h2>";
//Only display errors if they exist
if($e > 0)
{
     echo "<h3>Unable to download " . $e . " images</h2>";
}

Attachment.txt

This is the easiest possible way that I’ve found to handle a lengthy list of files, and it involves a super complicated list of files.  The magic trick you ask?  Hit the RETURN key after each file.  Your file contents should look something like…

https://www.phpdevtips.com/wp-content/uploads/2013/06/mini-180x160.png
https://www.phpdevtips.com/wp-content/uploads/2013/06/dev_tips-2.png
https://www.phpdevtips.com/wp-content/uploads/2014/06/wenger-180x160.jpg

That’s it.  No, really.

Download the whole script below!

[dm]16[/dm]

Leave a comment