Search code examples
phpfile-get-contentsfile-put-contents

Download to folder in server from url, PHP


I have in my database several image links in an array. I want to download these to a folder in my server renaming the images to 0.jpeg, 1.jpeg, 2.jpeg and so on. I only managed to insert 1 with the name of 0.jpeg.

$result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  

while ($row2 = $result2->fetch()){
    $arrays = $row2["myfoto"];
    foreach(json_decode($arrays) AS $url){
        //prints correctly all files 
        echo $url;
        file_put_contents('/home/my/public_html/place/fotos/[0].jpeg', 
        file_get_contents($url));
    }
 }

Solution

  • You need to use some kind of index that increases, and then can be used in the filename

    Easiest way with your current code is to use the index of the array of the results:

    $result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  
    
    while ($row2 = $result2->fetch()){
        $arrays = $row2["myfoto"];
        foreach(json_decode($arrays) AS $key => $url){
            //prints correctly all files 
            echo $url;
            file_put_contents('/home/my/public_html/place/fotos/'. $key . '.jpeg', file_get_contents($url));
        }
    }
    

    My preferred code would be:

    $result2 = $d->query("SELECT photos AS myfoto From table where id =  15");  
    
    while ($row2 = $result2->fetch()){
        $arrays = json_decode($row2["myfoto"]);
        foreach($arrays AS $key => $url){
            //prints correctly all files 
            echo $url;
            file_put_contents('/home/my/public_html/place/fotos/'. $key . '.jpeg', file_get_contents($url));
        }
    }
    

    not too fond of functions in a foreach-loop definition