在使用PHP的过程中,有些用户的配置是直接写在conf.php的。
当后台进行配置之后,这个时候就需要修改文件了,下面总结一些常用的函数,有兴趣的可以试试。
一、PHP读取文件
$data = file_get_contents("hello.php");
二、写入文件
$data = 'hello world'; file_put_contents ("test.txt", $data); // 写入指定文件替换) $str = file_get_contents('路径/文件.txt'); $update_str = str_replace('qwe=hello', 'qwe=Hello', $str); file_put_contents('路径/文件.txt', $update_str); ?>
三、删除文件
$result = @unlink ('text.txt'); //unlink 一般写的是绝对路径 if ($result == true) { echo '删除成功'; } //删除目录 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; } }
四、判断文件是否存在
// 远程判断 @$fp=fopen("http://www.loveteemo.com/Public/images/logo.png",'w'); if (!$fp){ echo '图片不存在'; exit; } // 当前服务器文件是否存在 <?php $file = "test.php"; if (file_exists($file) == false) { die('文件不存在'); } ?>
五、复制文件
//复制单个文件 $old = 'old.txt'; $new = 'new.txt'; //父文件夹必须能写 if (file_exists($old) == false) { die ('文件不存在,无法复制'); } $result = copy($old, $new); if ($result == false) { echo '复制成功'; } //复制整个目录 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);
上一篇: PHP时间轴函数...
下一篇: 2015驾照科二/三扣分点...