在Web开发中,我们经常需要实现文件上传的功能,尤其是在创建用户个人资料、发布文章或评论等场景中,PHP语言提供了一些内置的函数来帮助我们轻松实现这个功能,最为常用的就是使用PHP的move_uploaded_file()函数来上传和移动用户上传的文件,下面,我们将详细介绍如何使用这个函数。
我们需要了解move_uploaded_file()函数的基本语法:
bool move_uploaded_file ( string $filename , string $destination )
这个函数接受两个参数:$filename和$destination。$filename参数是用户上传的文件名,$destination参数是我们希望将文件移动到的目标路径。
在使用这个函数之前,我们需要确保以下几点:
1、用户已经选择了一个文件并点击了上传按钮。
2、我们已经通过$_FILES全局数组获取了用户上传的文件信息。
3、我们为目标路径设置了正确的权限,以便PHP可以写入文件。
下面是一个简单的PHP代码示例,演示如何使用move_uploaded_file()函数:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
在这个示例中,我们首先检查了用户是否已经选择了一个文件并点击了上传按钮,我们获取了用户上传的文件信息,并检查了文件的类型、大小和目标路径是否存在,我们使用move_uploaded_file()函数将文件移动到目标路径,如果文件成功上传,我们将显示一条消息告诉用户文件已成功上传,如果文件没有成功上传,我们将显示一条错误消息。



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