php: load images from urls and save local copy

Trabla: php: load images from urls and save local copy

In this tutorial we will create simple php image loader,
and .bat file to run it.

Solving:

1. Make sure php is installed in your system and environment variable "path" includes correct path to php.
Run CMD (windows command line) and execute following command:

php -version

PHP 5.5.24 (cli) (built: Apr 15 2015 12:57:23)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies


2. In any folder create following files:

image_loader.php
images.csv
run_image_loader.bat

3. Paste following code into file  image_loader.php :

<?php

    // No execution time limit
    @set_time_limit(0);

    // csv file should be placed in same folder as php script
    $csv = array_map('str_getcsv', file('images.csv'));

    foreach ($csv as &$row) {

        // First column in csv file - image url
        $url         = $row[0];
        // Second column in csv file - local file name
        $file_name     = $row[1];

        if( !file_exists($file_name)){

                echo "Loading {$url}\n";

                file_put_contents( $file_name ,  file_get_contents($url) );

                echo "Created {$file_name}\n";
        }


    }
    unset($row);

    echo "Done\n";

?>


4. In file images.csv place list of urls and local file name
Example:

http://i.istockimg.com/file_thumbview_approve/57425458/3/stock-photo-57425458-beautiful-mountains-in-the-arabian-desert.jpg, rocks.jpg
http://c.tadst.com/gfx/750x500/sunrise.jpg?1, sunrise.jpg


5. In file run_image_loader.bat place following script and replace path to yours:

CD C:\Users\SamuraiKit\Desktop\"Php Image Loader"
php image_loader.php
PAUSE


6. Run script - double click on file run_image_loader.bat

Example output:
 
Loading http://i.istockimg.com/file_thumbview_approve/57425458/3/stock-photo-574
25458-beautiful-mountains-in-the-arabian-desert.jpg
Created  rocks.jpg
Loading http://c.tadst.com/gfx/750x500/sunrise.jpg?1
Created  sunrise.jpg
Done



 

No comments:

Post a Comment