-->

PHP资讯

您的当前位置:首页 > 资讯 > PHP基础

php文件操作

2021-04-01 17:42:13  来源:admin 点击:463

一、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);


相关文章更多 >

© 2024版权所有 水水网

电话:171780793