'How to upload default picture if user delete the picture?

So, i want to make if user click the delete button the picture profile will be user.jpg (this is default picture).

enter image description here

here is my controller :

public function update()
{
    $fileimg = $this->request->getFile('img');
    $oldimg= $this->request->getVar('oldimage');
    $defaultimg= $this->request->getVar('defaultimage');
    
    if ($fileimg == 'user.jpg') {
        $uploadImg = $defaultimg;
    }
    if ($fileimg->getError() == 4) {
        $uploadImg= $oldimg;
    } else {
       
        $uploadImg = $fileimg->getRandomName();
        
        $fileimg->move('img/', $uploadImg);
        

        if ($oldimg != 'user.jpg') {

            unlink('img/' . $oldimg);
        }
    }

When i click delete button image the image will be user.jpg and then i click button upload but the image wont change to user.jpg, but always showing the old picture. sorry for bad english.



Solution 1:[1]

How about think like this:

Default picture is not a data which user is willingly save to database. It's rather a placeholder. Thinking further, it can be handled in the views. If user profile picture is not set or exists, show default picture. To prevent typing manually you can make it a global data or a config value or a constant. But the key is it is a placeholder, not a data.

Happy coding...

Solution 2:[2]

Write the image name in a database somewhere, usually in the user profile table. It will make your life much easier, and you'll be able to access it all the time. Then in your model, you'll be able to see if there is no image and return the default image.

I am not sure what your getRandomName() is doing, but some hash function (sha1, md5...) are good enough for creating a file name to avoid possible name collisions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YahyaE
Solution 2 neokio