2015-12-10 39 views
1

我在Laravel 5.1中有一个项目PHP中的文件安全和删除文件

而且我有产品图片。

我想删除图片文件,当我删除数据库中的产品。

我像根

img/product 

我有图片的版本

public function getVersions() 
{ 
    return [ 
     'large'  => '/large', 
     'medium' => '/medium', 
     'small'  => '/small', 
     'thumbnail' => '/thumbnail', 
     'root'  => '' 
    ]; 
} 

我的产品形象根

$productImageRoot = public_path('img/product/'.$product_id); 

我想了解以安全方式删除所有照片的最佳做法是什么?

这里是我删除产品的所有图片的代码。

/** 
    * @desc Ürün resimlerini ve resimlerin bulunduğu klasörleri siler. 
    * @param $product_id 
    * @return bool 
    * @throws \Exception 
    */ 
    public function deleteAllPictureFiles($product_id) 
    { 
     /** 
     * Resim türlerinin klasör yollarını çekiyoruz. 
     */ 
     $folderPaths  = $this->getVersions(); 

     $productImageRoot = public_path('img/product/'.$product_id); 

     $pictures   = (new ProductPicture)->getAllPicturesOfProduct($product_id); 

     try 
     { 
      /** 
      * Resim yolu yazılabilir ise... 
      */ 
      foreach($pictures as $picture) 
      { 
       /** 
       * Tüm resimleri siliyoruz. 
       */ 
       foreach($folderPaths as $folderPath) 
       { 
        unlink($productImageRoot.$folderPath.'/'.$picture->picture); 
       } 
      } 

      /** 
      * Tüm klasörleri siliyoruz. 
      */ 
      foreach($folderPaths as $folderPath) 
      { 
       rmdir($productImageRoot.$folderPath); 
      } 

      return TRUE; 
     } 
     catch(\Exception $e) 
     { 
      /** 
      * Resim yolu yazılamaz ise hata dönderiyoruz. 
      */ 
      throw new \Exception(trans('product.is_not_writable')); 
     } 

此代码导致路径不可写的错误。

现在是我不确切的话题。我想学习文件和文件夹的chmod选项。我在删除过程中应该怎么做?什么是最安全的删除文件的方式?我不想使用chmod 777.我知道这是不安全的。

+0

你尝试过使用775吗? –

回答

0

您可以使用Laravel删除目录更容易。

File::deleteDirectory('img/product/'.$product_id); 

而且你是对的,不要使用777 755应该工作。如果755不起作用,但是777起作用,那么该组可能是错误的,您可以使用chown -R youruser:yourgroup yourlaravelfolder修复它。很可能你的用户和团体将是一样的。

请务必在尝试任何此操作之前进行备份。