我在删除实体时使用此代码删除图像
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($this->filenameForRemove)
{
unlink ( $this->filenameForRemove );
}
}
但问题是,如果我没有那里的图像,那么它会像这样抛出异常
Warning: unlink(/home/site/../../../../uploads/50343885699c5.jpeg) [<a href='function.unlink'>function.unlink</a>]: No such file or directory i
有没有办法,如果文件不存在或目录不存在,它应跳过此步骤仍然删除实体
答案 0 :(得分:3)
您可以使用file_exists
确保文件确实存在,并使用is_writable
确保您有权删除该文件。
if ($this->filenameForRemove)
{
if (file_exists($this->filenameForRemove) &&
is_writable($this->filenameForRemove))
{
unlink ( $this->filenameForRemove );
}
}
答案 1 :(得分:0)
Symfony引入了文件系统组件。您可以检查文档here。它说:The Filesystem component provides basic utilities for the filesystem.
例如,您可以像这样删除文件之前检查文件路径/目录是否存在:
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
}