How to download an image from a URL?

1

How do I download an image from a URL using PHP and save it to a folder to use later? I want to save IMDb images for use on my own site.

First I tried to download the image using PHP's copy x function but nothing happened

copy($info->Poster, "Posters");

$info->Poster is the direct link to the image.

    
asked by anonymous 11.01.2016 / 22:30

1 answer

2

The first is to make sure that the destination folder on the server has the correct permissions. I tested with this PHP manual code and it worked ok, you would have to check the error logs on your server , but it looks like the code below might help with this:

<?php
$imgurl = 'http://ia.media-imdb.com/images/M/MV5BNTA2MTk3NzI5Ml5BMl5BanBnXkFtZTgwNzU2MzYyNzE@._V1_SX300.jpg';
if( !@copy( $imgurl, './teste.jpg' ) ) {
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />\n".$errors['message'];
} else {
    echo "File copied from remote!";
}

I used the OMDb API - The Open Movie Database to get to Movie Poster URL .

And I tested this other code, from the Copy to my direct URL from URL and it also worked (attention to the paths and permissions of the folder):

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $useragent);         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://ia.media-imdb.com/images/M/MV5BMjE0NDUzMDcyOF5BMl5BanBnXkFtZTcwNzAxMTA2Mw@@._V1_SX300.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('./'.$imagename,$image); 

As a copyright notice in this case, usually movie posters are freely distributed by the producer itself, at least it was in all the feature films that I have been involved in and whose website makes the poster available for download.

12.01.2016 / 02:36