3

I created an application to upload image using PHP, Javascript and WAMP server. I need to deleted automatically the uploaded image after some time, say X mins. How this can be achieved?

Thanks...

Nidhish
  • 361
  • 1
  • 3
  • 17
  • 1
    You can set cronjob method on server which will delete all images inside any folder.. – Dhara Parmar May 03 '16 at 06:20
  • You could have a cron job running every N minutes that would delete all files older than X mins (using find & rm for example). There is no real point using PHP to do that here – lisa May 03 '16 at 06:23
  • he is running WAMP, which is a Windows thing. So he probably doesn't know what you mean. – Ruslan Osmanov May 03 '16 at 06:28
  • @RuslanOsmanov Exactly. here is what a cron is http://www.thesitewizard.com/general/set-cron-job.shtml - once you know what this is, you should be able to understand what you need to do next – Ritesh Ksheersagar May 03 '16 at 06:30
  • Look up `Windows Task Scheduler`. Create a `PHP CLI Script` to do what you want and schedule it however often you want to, or maybe you can do it with a simple `.bat` or `.cmd` file instead – RiggsFolly May 03 '16 at 14:53
  • @DharaParmar WAMP.... The W stands for `Windows` therefor no cron use Task Scheduler instead – RiggsFolly May 03 '16 at 14:54

2 Answers2

1

Try this Solution:

    <?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;
        }

    ?>

Here is the Javascript that glues the whole Process...

    <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>
Poiz
  • 7,611
  • 2
  • 15
  • 17
0

Cron Job is the right tool you need. Cron in windows is a little hard to achieve by using php. if youa are using a framework its easy to do it. But the following links will help you achieve your goal.

How to create cron job using PHP?

Run Cron Job on PHP Script, on localhost in Windows

Community
  • 1
  • 1