php文件基本操作函数

3153

一、PHP读取文件

$data = file_get_contents("test.php");

二、写入文件

$data = 'PHP'; 
file_put_contents ("test.txt", $data); //如果文件不存在 则自动创建一个文件

三、删除文件

1.删除单个文件

$result = @unlink ('./text.txt'); //传入绝对路径
if ($result == true) { 
 echo '删除成功'; 
}

2.删除整个目录

function deldir($dir) { 
    //先删除目录下的文件: 
    $dh = opendir($dir); 
    while ($file = readdir($dh)) { 
        if ($file != "." && $file != "..") { 
            $fullpath = $dir . "/" . $file; 
            if (!is_dir($fullpath)) { 
                unlink($fullpath); 
            } else { 
                deldir($fullpath); //递归删除
            } 
        } 
    } 
    closedir($dh); 
    //删除当前文件夹: 
    if (rmdir($dir)) { 
        return true; 
    } else { 
        return false; 
    } 
}

四、判断文件是否存在

1.远程判断

@$fp = fopen("http://www.sucaihuo.com/Public/images/logo.png",'w'); 
if (!$fp){ 
    echo 'logo不存在'; 
    exit; 
}

2.当前服务器文件是否存在

<?php 
$file = "test.php"; 
if (file_exists($file) == false) { 
  die('文件不存在'); 
} 
?>

五、复制文件

1.复制单个文件

$old = 'old.txt'; 
$new = 'new.txt'; # 这个文件父文件夹必须能写 
if (file_exists($old) == false) { 
  die ('文件不存在,无法复制'); 
} 
$result = copy($old, $new); 
if ($result == false) { 
  echo '复制成功'; 
}

2.复制整个目录

function recurse_copy($src, $dst) {  // 原目录,复制到的目录 
    $dir = opendir($src); 
    @mkdir($dst); 
    while (false !== ( $file = readdir($dir))) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if (is_dir($src . '/' . $file)) { 
                recurse_copy($src . '/' . $file, $dst . '/' . $file); 
            } else { 
                copy($src . '/' . $file, $dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
}

六、遍历文件

$file_path = "test/"; 
$files = scandir($file_path); 
print_r($files);