Mirage
Mirage

Reputation: 31548

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

Upvotes: 1

Views: 4974

Answers (2)

Ngatia Frankline
Ngatia Frankline

Reputation: 3216

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
}

Upvotes: 0

drew010
drew010

Reputation: 69957

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 );
    }
}

Upvotes: 3

Related Questions