Skip to content

文件与目录操作

文件读取与写入

  • fopen():打开文件,返回文件指针,用于读取或写入。

    php
    $file = fopen("example.txt", "r"); // 以只读模式打开文件
    if ($file) {
        // 操作文件
        fclose($file); // 关闭文件
    }
  • fread():读取文件内容。

    php
    $file = fopen("example.txt", "r");
    if ($file) {
        $content = fread($file, filesize("example.txt")); // 读取文件内容
        echo $content;
        fclose($file);
    }
  • fwrite():写入文件。

    php
    $file = fopen("example.txt", "w"); // 以写入模式打开文件
    if ($file) {
        fwrite($file, "Hello, World!"); // 写入内容
        fclose($file);
    }
  • file_get_contents():读取文件的全部内容到一个字符串中。

    php
    $content = file_get_contents("example.txt");
    echo $content;
  • file_put_contents():将字符串写入文件。

    php
    file_put_contents("example.txt", "Hello, PHP!"); // 覆盖写入
    file_put_contents("example.txt", "Hello again!", FILE_APPEND); // 追加写入

文件上传与下载

文件上传:

上传文件时,需在 HTML 表单中使用 enctype="multipart/form-data"

html
<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload">
    <input type="submit" value="Upload">
</form>

处理文件上传(upload.php):

php
if (isset($_FILES['fileToUpload'])) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

文件下载:

php
$file = "path/to/file.txt";
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

目录操作

创建目录:

使用 mkdir() 创建一个新目录。

php
if (!file_exists("new_directory")) {
    mkdir("new_directory", 0755, true); // 0755 表示权限,true 表示递归创建
}

删除目录:

使用 rmdir() 删除一个空目录。

php
if (file_exists("new_directory")) {
    rmdir("new_directory");
}

遍历目录:

使用 scandir() 列出目录中的文件和子目录。

php
$files = scandir("path/to/directory");
foreach ($files as $file) {
    if ($file !== "." && $file !== "..") {
        echo $file . "\n";
    }
}

删除非空目录:

可以递归删除非空目录中的文件和子目录。

php
function deleteDir($dir) {
    if (!is_dir($dir)) {
        return;
    }
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file !== "." && $file !== "..") {
            $filePath = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($filePath)) {
                deleteDir($filePath); // 递归删除子目录
            } else {
                unlink($filePath); // 删除文件
            }
        }
    }
    rmdir($dir); // 删除目录
}

deleteDir("path/to/non_empty_directory");
编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!