简体   繁体   中英

How can i unlink file for removal in symfony2

I a using this code for image removal when i delete the entity

  /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if ($this->filenameForRemove)
        {
            unlink ( $this->filenameForRemove );
        }
    }

But the problem is if i don't have the image there then it throws exception like this

Warning: unlink(/home/site/../../../../uploads/50343885699c5.jpeg) [<a href='function.unlink'>function.unlink</a>]: No such file or directory i

Is there any way that if file is not there or directory is not there it should skip this step and still deletes the entity

You can use file_exists to make sure the file actually exists and is_writable to make sure you have permission to remove it.

if ($this->filenameForRemove)
{
    if (file_exists($this->filenameForRemove) &&
        is_writable($this->filenameForRemove))
    {
        unlink ( $this->filenameForRemove );
    }
}

Update

Symfony has introduced the The Filesystem Component. You can check the docs here . It says: The Filesystem component provides basic utilities for the filesystem.

For example you can check if the file path/directory exists before deleting your file like this:

use Symfony\Component\Filesystem\Filesystem;


$filesystem = new Filesystem();
$oldFilePath = '/path/to/directory/activity.log'

if($filesystem->exists($oldFilePath)){
    $filesystem->remove($oldFilePath); //same as unlink($oldFilePath) in php
}

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