PHP操作文件大全
作者: zms!
日期: 2018.05.09 本文发布于690天前
分类: PHP函数语法点滴
相关:
一、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.erdangjiade.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);
讨论区
你可能也喜欢
dbMySQL数据源访问类 2020.03.14,7 pv
php计算当前时间到以后一天、一周、一月、一年 2020.01.12,1 pv
php防止CC攻击代码 php防止网页频繁刷新 2019.06.12,7 pv
php将手机号转为字符串并求所有数字之和,或求字符串中所有数字之和的两个方法: 2018.10.15,15 pv
PHP环境加固,让黑客无从下手 2018.05.15,11 pv
PHP支持手势的手机端图片裁剪上传 2018.05.09,9 pv