繁体   English   中英

我如何取消链接文件以在 symfony2 中删除

[英]How can i unlink file for removal in symfony2

当我删除实体时,我使用此代码进行图像删除

  /**
     * @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

有没有办法,如果文件不存在或目录不存在,它应该跳过这一步并仍然删除实体

您可以使用file_exists来确保文件确实存在,并使用is_writable来确保您有权删除它。

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

更新

Symfony 引入了文件系统组件。 您可以在此处查看文档。 它说: 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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