PHP文件操作与上传下载的艺术
在Web开发的世界里,文件操作与上传下载是不可或缺的技能。PHP作为一种广泛使用的后端语言,提供了强大的文件处理功能。本文将带你深入探索PHP中的文件操作技巧,以及如何实现高效、安全的文件上传与下载。

文件操作基础
打开与关闭文件
在PHP中,文件操作的第一步是打开文件。fopen()函数用于打开文件,并返回一个文件指针。示例如下:
$file = fopen("example.txt", "r");
这里,"r"表示以只读模式打开文件。文件打开后,别忘了用fclose()关闭它:
fclose($file);
读取文件内容
读取文件内容有多种方式,最简单的是file_get_contents():
$content = file_get_contents("example.txt");
echo $content;
如果你需要逐行读取,可以使用fgets():
$file = fopen("example.txt", "r");
while (!feof($file)) {
$line = fgets($file);
echo $line;
}
fclose($file);
写入文件
写入文件同样简单,file_put_contents()可以一次性写入内容:
$content = "Hello, World!";
file_put_contents("example.txt", $content);
若需追加内容,可以使用fopen()配合fwrite():
$file = fopen("example.txt", "a");
fwrite($file, "\nAppending this line.");
fclose($file);
文件上传
文件上传是Web应用中的常见需求。PHP通过$_FILES数组接收上传的文件信息。
上传表单
首先,创建一个HTML表单:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" />
<input type="submit" value="Upload" />
</form>
处理上传文件
在upload.php中,处理上传的文件:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// 检查文件是否真实上传
if (isset($_FILES["fileToUpload"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 检查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件大小
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许特定文件格式
if ($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查是否$uploadOk被设置为0由于一个错误
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
文件下载
文件下载同样简单。以下是一个示例:
$file = "path/to/your/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('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
这段代码首先检查文件是否存在,然后设置适当的HTTP头,最后使用readfile()函数将文件内容发送到浏览器。
安全
« 上一篇
PHP会话管理与Cookies的艺术
下一篇 »
PHP表单处理与用户输入验证的艺术