[英]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.您可以使用
file_exists
来确保文件确实存在,并使用is_writable
来确保您有权删除它。
if ($this->filenameForRemove)
{
if (file_exists($this->filenameForRemove) &&
is_writable($this->filenameForRemove))
{
unlink ( $this->filenameForRemove );
}
}
Symfony has introduced the The Filesystem Component. Symfony 引入了文件系统组件。 You can check the docs here .
您可以在此处查看文档。 It says:
The Filesystem component provides basic utilities for the filesystem.
它说:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.