Laravel 4.x:如何删除文件?

时间:2014-04-09 06:08:05

标签: php file-io laravel-4

我有一个表名的图像。它有id,name,url和timestamp字段。

这是我的代码:

$image=Image::find($id);
$url=$image->url;
if(unlink("$url")){
    $image->delete();
    return true;
}else
    return false;

它不起作用,所以我回复了我得到的网址:

http://localhost/project/public/uploads/gallery/1/_DSC845645490.jpg

但是当我检查它时:

if(file_exists(Image::find($id)->url)){
            return 'has image';
        }else{
            return 'no image';
        }

我已经'没有形象',但我可以在网络浏览器上显示图像

为什么?有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

我使用过这个,每次使用时它都有用

File::delete(public_path('img/slider/').$delete_image);

此处 $ delete_image 是文件的名称,用 public_path()方法编写的路径是从laravel yourProject / public /的根文件夹开始的路径

答案 1 :(得分:0)

Illuminate \ Filesystem \ Filesystem类中的方法(请参阅http://laravel.com/api/4.1/并搜索' filesystem')。

您可以像这样调用 delete 方法

File::delete(path/to/file/relative/to/public/folder);
顺便说一句:也许你的代码很好,但你在url领域有什么?如果它是相对的,你还必须在它之前加上像

这样的东西
<?php 
  if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg"))  { 
    ... 
  } 
?> 

(来自http://www.php.net/manual/en/function.file-exists.php的例子)