模式切换
文件与目录操作
文件读取与写入
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()
:将字符串写入文件。phpfile_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");