[英]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.