phpdelete-fileunlinkremove-if

Remove (delete, replace or unlink) old image file while updating


I have implemented the (bulletproof) uploader in my script. But when I try to update my records by changing the DB table row for example:

I want to update and (replace) the old game image with a new game image (I am using a rename method)! I find that the new image uploaded and renamed successfully, but the old image still exists in the thumbs folder.

Here is my code:

$newthumb=false;
if($continue){
    $bulletProof = new ImageUploader\BulletProof;

    try{    
    if($_FILES && $_FILES['avaimage']['name']){
    $name3=strtolower($game_name);
    $name3=str_replace(' ', '-',$name3);
    $thumbnail=$name3.'-'.generateRandomString();
    $pic1=$bulletProof->uploadDir("../thumbs")->shrink(array("height"=>200, "width"=>200))->upload($_FILES['avaimage'],$thumbnail);
    if($pic1){
    $thumb=$pic1;
    }
    }
    }catch(\ImageUploader\ImageUploaderException $e){
     $error=$e->getMessage();
    $continue=false;
    }
}

I used to delete the old files while updating to prevent exhausted disk space and keep my site clean and easy to manage, but this way if I changed the game image 10 times, I'll get 10 diff images and so on, This is a bad thing.

This is what I get:

dub_img

I can explain as follow:

1- User edit profile 2- User choose a photo for the profile 3- User click save to update the profile.

Each time the user uploads a new (or even the same profile photo) it uploaded (and renamed) to be as if a new one, and leave the old (prev photo) intact.

Screenshot#1 ٢٠١٩-٠٦-١٨ at ١٨-٠٠-٣١

٢٠١٩-٠٦-١٨ at ١٨-٠١-١٥

٢٠١٩-٠٦-١٨ at ١٨-٠١-٤٩

So, a new photo uploaded without removing the old one, If I have 1 million users, and every user uploaded 10 photos (and only uses 1) then I'll get 9 million unused orphaned files.

Even if I refreshed the page, a new photo uploaded (because of browser history). Check this#: I click refresh 4 times (before leaving the page)

٢٠١٩-٠٦-١٨ at ١٨-٠٦-١٤

And I get this: ٢٠١٩-٠٦-١٨ at ١٨-٠٦-٣٢.

Can you imagine how orphaned files are there?

Any help will be appriciated.

I am using PHP PDO for updating the records.

Thanks


Solution

  • Okay! thank you everyone for watching this. I have come up with a solution, as follow:

    if($_FILES && $_FILES['avaimage']['name']){
    //check current photo
    $stmt = $db->prepare("SELECT avatar FROM users WHERE id=:uid LIMIT 1");
    $stmt->bindValue(':uid', $uid, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $icheck=$result[0];
    if ($icheck['avatar']) {
    @unlink("images/avatars/".$icheck['avatar']);
    }else{
    $error='Please check photo';
    $continue=false;    
    }
    }
    

    Now, Only one photo can be uploaded and nothing more can be added if the user refreshed the page, only one image will be there.

    Thank you.