PHP 提供了一系列用于处理文件和目录的函数,这些函数被统称为文件系统函数。以下是一些基本的 PHP 文件系统函数的用法:

文件操作:

1. 读取文件内容:
$fileContent = file_get_contents('/path/to/file.txt');
echo $fileContent;

2. 写入文件内容:
$fileContent = 'Hello, World!';
file_put_contents('/path/to/file.txt', $fileContent);

3. 追加内容到文件:
$fileContent = 'New content to append.';
file_put_contents('/path/to/file.txt', $fileContent, FILE_APPEND);

4. 检查文件是否存在:
$filePath = '/path/to/file.txt';
if (file_exists($filePath)) {
    echo 'File exists!';
} else {
    echo 'File does not exist.';
}

5. 获取文件大小:
$fileSize = filesize('/path/to/file.txt');
echo 'File size: ' . $fileSize . ' bytes';

6. 删除文件:
$filePath = '/path/to/file.txt';
unlink($filePath);

目录操作:

1. 创建目录:
$directoryPath = '/path/to/new/directory';
mkdir($directoryPath, 0755, true); // 0755 是权限设置,true 表示递归创建目录

2. 删除目录(如果为空):
$directoryPath = '/path/to/directory/to/delete';
rmdir($directoryPath);

3. 递归删除目录及其内容:
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }

    return rmdir($dir);
}

$directoryPath = '/path/to/directory/to/delete';
deleteDirectory($directoryPath);

4. 复制文件或目录:
$source = '/path/to/source';
$destination = '/path/to/destination';

// 如果 $source 是目录,使用递归复制
if (is_dir($source)) {
    if (!file_exists($destination)) {
        mkdir($destination, 0755, true);
    }

    $files = scandir($source);

    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            copy($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
        }
    }
} else {
    copy($source, $destination);
}

这只是 PHP 文件系统操作的一些基本示例。在实际应用中,你可能需要处理更复杂的文件和目录结构,确保在操作文件和目录时考虑到安全性和权限问题。


转载请注明出处:http://www.zyzy.cn/article/detail/13855/PHP