PHP一段时间后自动删除上传的图像

时间:2016-05-03 06:19:00

标签: php file upload wamp

我创建了一个使用PHP,Javascript和WAMP服务器上传图像的应用程序。 X分钟后,我需要在一段时间后自动删除上传的图像。如何实现这一目标?

...谢谢

2 个答案:

答案 0 :(得分:1)

试试这个解决方案:

    <?php
        /**
         * FileName: ajax-processor.php
         */
        $uploadDir  = __DIR__ . "/uploads";   // HERE: YOU SPECIFY THE PATH TO THE UPLOAD DIRECTORY
        $action     = isset($_POST['action'])   ? htmlspecialchars(trim($_POST['action']))      : null;
        $imageAge   = isset($_POST['imageAge']) ? htmlspecialchars(trim($_POST['imageAge']))    : 24;

        // IF AJAX TELLS US TO DELETE ALL IMAGES & GIVES US THE MAXIMUM AGE OF THE IMAGES TO BE DELETED
        // WE NOW FIRE THE COMMANDS BELOW.
        // NOTE THAT USING THE imageAge WE CAN DECIDE THE FILES THAT WOULD BE DELETED SINCE WE DON'T WANT ALL DELETED
        // THE DEFAULT HERE WOULD BE 24 HOURS...
        if($action=="delete" && $imageAge>0){
            $deletionReport = removeImagesInFolder($uploadDir, $imageAge);
            return json_encode($deletionReport);
        }

        function getImagesInFolder($dir_full_path){
            $returnable     = array();
            $files_in_dir   = scandir($dir_full_path);
            $reg_fx         = '/(\.png$)|(\.jpg$)|(\.jpeg$)|(\.tiff$)/';
            foreach($files_in_dir as $key=>$val){
                $temp_file_or_dir = $dir_full_path . DIRECTORY_SEPARATOR . $val;
                if(is_file($temp_file_or_dir) && preg_match($reg_fx,  $val) ){
                    $regx_dot_wateva            = '/\.{2,4}$/';
                    $regx_dot                   = '/\./';
                    $regx_array                 = array($regx_dot_wateva, $regx_dot);
                    $replace_array              = array("", "_");
                    $return_val                 = preg_replace($regx_array, $replace_array, $val);
                    $returnable[$return_val]    = $temp_file_or_dir ;
                }else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
                    getImagesInFolder($temp_file_or_dir);
                }
            }
            return $returnable;
        }

        function removeImagesInFolder($imgFolder, $imageAgeInHours=24){
            //CHANGE FILE-PERMISSION ON THE IMAGE DIRECTORY SO YOU COULD WORK WITH IT.
            chmod($imgFolder, 0755);

            $arrImages          = getImagesInFolder($imgFolder);
            $statusReport       = array();
            foreach($arrImages as $imgKey=>$imageFile){
                $imageAgeInSecs     = $imageAgeInHours*60*60;
                if (file_exists($imageFile)) {
                    $now            = time();
                    $fileModTime    = filemtime($imageFile);
                    $fileAge        = ($now - $fileModTime);

                    if($fileAge >= $imageAgeInSecs){
                        /* BE CAREFUL: THE GIVEN FILE WOULD ACTUALLY BE DELETE!!! */
                        //HERE IS A LITTLE ADDITION FOR PERMISSION ISSUES
                        //NOTE THAT I DID NOT TEST THIS SINCE I AM NOT ON A WINDOWS SYSTEM & I DON'T USE WAMP... BUT I THINK THIS MAY DO THE TRICK
                        //CHANGE FILE-PERMISSION ON THE IMAGE FILE SO YOU COULD DELETE IT.
                        chmod($imageFile, 0755); //GIVES THE ADMINISTRATOR RIGHT TO DO EVERYTHING WITH THE FILE; BUT ALLOWS ONLY READING/EXECUTION FOR OTHER USERS.
                        if( unlink($imageFile) ) {

                            $statusReport[] = "Deleted " . $imageFile . ". This File is about " . ($fileAge / (24 * 60 * 60)) . " Day(s) Old.";
                        }
                    }
                }
            }
            return $statusReport;
        }

    ?>

这是粘合整个过程的Javascript ......

    <script type="text/javascript">
        (function($) {
            $(document).ready(function(){
                var iInterval   = setInterval(deleteImagesViaAjax, 1000*60+60);    //DELETE IMAGES EVERY HOUR

                function deleteImagesViaAjax(){
                    $.ajax({
                        url: "http://localhost/framework/ajax-processor.php",
                        dataType: "json",
                        cache: false,
                        type: "POST",
                        data: ({
                            action      : 'delete',
                            imageAge    : 24            //MAXIMUM AGE OF THE IMAGE TO DELETE IN HOURS - THIS MEANS ALL IMAGES UPLOADED ABOUT 24 HOURS AGO 
                        }),

                        success: function (data, textStatus, jqXHR) {
                            console.log(data);
                        },

                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log('The following error occured: ' + textStatus, errorThrown);
                        },

                        complete: function (jqXHR, textStatus) {
                        }
                    });
                }

            });
        })(jQuery);
    </script>

答案 1 :(得分:0)

Cron Job是您需要的正确工具。 Windows中的Cron使用php有点难以实现。如果你使用框架,它很容易做到。但以下链接将帮助您实现目标。

How to create cron job using PHP?

Run Cron Job on PHP Script, on localhost in Windows