php删除文件程序代码
在php中要删除文件我们需要使用php提供的unlink()文件删除函数,下面我来给大家详细介绍利用unlink删除文件的方法,有需要的朋友可参考本教程。
unlink(filename,context)
例代码如下:
- if (unlink($file_delete)) {
- echo "The file was deleted successfully.", "n";
- } else {
- echo "The specified file could not be deleted. Please try again.", "n";
- }
判断文件是否存在,代码如下:
- $myfile = "./test1.txt";
- if (file_exists($myfile)) {
- $result=unlink ($myfile);
- echo $result;
- }
批量删除文件,代码如下:
- function delFileUnderDir( $dirName="../Smarty/templates/templates_c" )
- {
- if ( $handle = opendir( "$dirName" ) ) {
- while ( false !== ( $item = readdir( $handle ) ) ) {
- if ( $item != "." && $item != ".." ) {
- if ( is_dir( "$dirName/$item" ) ) {
- delFileUnderDir( "$dirName/$item" );
- } else {
- if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item<br />n";
- }
- }
- }
- closedir( $handle );
- }
- }delDirAndFile( 'www.phpfensi.com');
删除目录下文件并指定那些不删除,代码如下:
- <?php
- header("content-Type: text/html; charset=utf-8");
-
- $path=".";
- $guolv="del.php,install.php,path";
-
- if($_GET['action']=="del"){
- $file= array_values_recursive(recurdir($path,$guolv));
- foreach($file as $k => $v){
- remove_directory($v);
- }
- }else{
- echo "您的配置如下<br>
- 要删除的目录为:
- ";
- if($path==".")echo "当前目录";else echo $path;
- echo "<br>您要过滤的文件或文件夹有:".$guolv."<br>
- 如果确认过滤请<a href='?action=del'>点击此处开始删除相应的目录及目录下的所有文件</a>,如果配置不正确请到文件中修改
- ";
- }
-
-
- function remove_directory($dir) {
- foreach(glob($dir) as $fn) {
- echo " removing $fn<br>n";
- if (!is_writable($fn))@chmod($fn, 0777);
- if(is_dir($fn)){@rmdir($fn);}else{@unlink($fn);}
- }
- }
-
- function recurdir($pathname,$guolv='del.php')
- {
- $result=array();$temp=array();
-
- if(!is_dir($pathname) || !is_readable($pathname))
- return null;
-
- $allfiles=scandir($pathname);
- foreach($allfiles as $key => $filename)
- {
-
- if(in_array($filename,array('.','..')))continue;
- if(count($guolv)>0){$lv=explode(",",$guolv);if(in_array($filename,$lv))continue;}
-
-
- $fullname =$pathname . "/" .$filename;
-
- $temp[]=$fullname;
- if(is_dir($fullname)){
- $nowpath=explode("/",$fullname);
- if(count($guolv)>0){$lv=explode(",",$guolv);if(in_array($nowpath[count($nowpath)-1],$lv))continue;}
- $result[$filename] = recurdir($fullname);}
- }
-
- foreach($temp as $f){
- $result[]=$f;
- }
- return $result;
- }
-
- function array_values_recursive($ary)
- {
- $lst = array();
- foreach( array_keys($ary) as $k ){
- $v = $ary[$k];
- if (is_array($v)) {$lst = array_merge( $lst, array_values_recursive($v));}else{$lst[] = $v;}
- }
- return $lst;
- }
- ?>