且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像从网址复制到服务器,删除之后的所有图像

更新时间:2023-12-05 17:23:58

在循环中使用file_get_contents或cURL

use file_get_contents or cURL in a loop

    <?php 

    //loop with a list of images
    loop{
    $imgurl = 'url to image';
    $imagename= basename($imgurl);
    if(file_exists('./images_folder/'.$imagename)){continue;}
    $image = file_get_contents($imgurl);
    file_put_contents('images_folder/'.$imagename,$image);
    }
    ?>

    or cURL 

    <?php 
    //loop this
loop{
    $imgurl = 'url to image';
    $imagename= basename($imgurl);
    if(file_exists('./images_folder/'.$imagename)){continue;}
    $image = getimg($imgurl);
    file_put_contents('images_folder/'.$imagename,$image);
}
    ?>




   <?php
    //cURL function (outside of loop) to get img
        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;
        }
    ?>

在您要删除的服务器上的文件中,循环一旦你得到所有的图像

in a file on your server that you want deleted put this in it and call it at END of your loops once you got all the images

<?php 
function rrmdir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
            }
        }
        reset($objects);
        rmdir($dir);
        mkdir($dir);
    }
}

rrmrir('./products');
?>