Home >Backend Development >PHP Tutorial >PHP code example to delete temporary files

PHP code example to delete temporary files

不言
不言forward
2018-10-26 16:56:592904browse

The content of this article is about the code example of deleting temporary files in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We sometimes need to delete the newly generated temporary files. For example, when uploading or generating images, we need to store them locally now and then upload them to the image. server. After the image is uploaded to the server, the locally stored image is useless. In order to avoid the project file being too large, it becomes necessary to delete the local image file.

Share a piece of code directly:

//需要传两个参数,一个是我们需要删除的文件路径,比如:
  $path2= "./upload/picture/";
      $this->delDirAndFile($path,true);

//这是删除的方法
  public function delDirAndFile($path, $delDir = true) {
     if (is_array($path)) {
       foreach ($path as $subPath)
         $this->delDirAndFile($subPath, $delDir);
     }
     if (is_dir($path)) {
       $handle = opendir($path);
       if ($handle) {
         while (false !== ( $item = readdir($handle) )) {
           if ($item != "." && $item != "..")
             is_dir("$path/$item") ?  $this->delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
         }
         closedir($handle);
         if ($delDir)
           return rmdir($path);
       }
     } else {
       if (file_exists($path)) {
         return unlink($path);
       } else {
         return FALSE;
       }
     }
     clearstatcache();
   }

The above will delete the code part of the folder or file.

The above is the detailed content of PHP code example to delete temporary files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete