欢迎访问宙启技术站
智能推送

PHP文件操作函数常用操作示例

发布时间:2023-09-29 21:07:09

PHP文件操作函数是用来处理文件的函数,包括创建、打开、读写、删除等操作。下面是常用的PHP文件操作函数及其示例:

1. fopen() 打开文件

$file = fopen("test.txt", "r"); // 以只读方式打开文件

2. fclose() 关闭文件

fclose($file); // 关闭文件

3. fwrite() 写入文件

$file = fopen("test.txt", "w"); // 以写入方式打开文件
fwrite($file, "Hello, World!"); // 写入内容
fclose($file); // 关闭文件

4. fgets() 逐行读取文件

$file = fopen("test.txt", "r"); // 以只读方式打开文件
while(!feof($file)) {
  echo fgets($file) . "<br>"; // 逐行输出文件内容
}
fclose($file); // 关闭文件

5. file_get_contents() 读取整个文件内容

$fileContent = file_get_contents("test.txt"); // 读取文件内容
echo $fileContent; // 输出文件内容

6. file_put_contents() 写入整个文件内容

$fileContent = "Hello, World!"; // 文件内容
file_put_contents("test.txt", $fileContent); // 写入文件

7. file_exists() 检查文件是否存在

if(file_exists("test.txt")) {
  echo "文件存在";
} else {
  echo "文件不存在";
}

8. unlink() 删除文件

unlink("test.txt"); // 删除文件

9. rename() 重命名文件

rename("test.txt", "new_test.txt"); // 将文件重命名为 new_test.txt

10. mkdir() 创建目录

mkdir("test_dir"); // 创建目录

11. rmdir() 删除目录

rmdir("test_dir"); // 删除目录

以上是PHP文件操作函数的常用操作示例,可以根据实际需求选择适合的函数进行文件操作。在实际开发中,要注意文件权限、文件路径等问题,确保文件操作的安全性和正确性。