简体   繁体   中英

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.

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM