在Web开发中,文件上传是一个常见的需求,无论是用户上传个人照片,还是网站管理员上传备份文件,都需要使用到文件上传功能,PHP作为一种广泛使用的服务器端脚本语言,提供了强大的文件处理能力,包括文件上传,本文将详细介绍如何在PHP中实现文件上传。
我们需要了解PHP中的$_FILES全局变量,当用户通过表单提交文件时,PHP会将文件信息存储在这个全局变量中。$_FILES是一个关联数组,其键名是表单字段的名称,值是一个包含了文件信息的数组,这个数组包含了以下几个元素:
- 'name':客户端提供的文件名。
- 'type':文件类型。
- 'size':文件大小,以字节为单位。
- 'tmp_name':临时存储文件的路径和名称。
- 'error':错误代码,0表示没有错误,其他值表示有错误发生。
了解了$_FILES全局变量后,我们就可以开始编写文件上传的代码了,以下是一个简单的文件上传的例子:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} 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.";
}
}
}
?>
这个例子中,我们首先检查请求方法是否为POST,然后获取用户上传的文件信息,并检查文件的类型、大小、是否存在以及是否为允许的文件格式,如果所有检查都通过,我们就尝试将文件移动到指定的目录,如果文件成功上传,我们就输出一条成功的消息;否则,我们就输出一条错误消息。



还没有评论,来说两句吧...