PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] Remove unused Images/files from upload folder laravel

 March 11, 2022     laravel, laravel-5.4     No comments   

Issue

I have laravel5.4 application.I want to remove unused images/files from my upload folder which is not available in my database.

For example : I have 50 images in my upload folder for user profile but some of the image not use for any user.i think he removed or update his image from frontend.

Yes i know we need to code to remove file when user update or remove profile picture at a time also delete from upload folder.but my app run from many time and i want to remove unused file using script not manually beacause i have lot's of files so it's hard to check and remove file manually.anyone can you please help me for create any function for remove file from folder.

Sorry for my bad English.


Solution

I use something like this in my AdminController to remove images by clicking on a button.
Maybe you need to change the path or extensions

public function deleteUnusedImages()
{
    $file_types = [
        'gif',
        'jpg',
        'jpeg',
        'png'
    ];
    $directory = public_path();
    $files = File::allFiles($directory);
    
    foreach ($files as $file)
    {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $file_types)) {
            
            if(DB::table('users')->where('votes', '=', $file)->count())
                continue; // continue if the picture is in use
            
            echo 'removed' . basename($file)."<br />";
            unlink($file); // delete if picture isn't in use
        }
    }
}


Answered By - julianstark999
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing