php如何删除临时文件

2023-03-02,

php删除临时文件的方法:首先打开相应的PHP文件;然后在文件中传入两个参数,其中一个是需要删除的文件路径;接着创建一个delDirAndFile方法用于实现删除功能;最后保存文件即可。

推荐:《PHP教程》

php删除文件夹(临时文件)代码

我们有时候需要删除刚生成的临时文件,比如上传图片或者生成图片的时候,我们需要现在本地存储起来,然后再上传到图片服务器。当图片上传到服务器之后,那本地存储的图片就没用了,为了避免项目文件过大,所以删除本地的图片文件的就变得很有必要。

直接分享一段代码:

//需要传两个参数,一个是我们需要删除的文件路径,比如:
  $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();
   }

以上就删除文件夹或者文件的代码部分。(顺便吐槽一句,编辑器的代码颜色看起来真难看。。。)

以上就是php如何删除临时文件的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《php如何删除临时文件.doc》

下载本文的Word格式文档,以方便收藏与打印。