引言
一、PHP图片上传基础
1.1 HTML表单设计
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
在这段代码中,enctype="multipart/form-data" 属性指定了表单的编码类型,使其能够处理文件数据。同时,表单的 action 属性指向一个 PHP 脚本,该脚本将处理上传的文件。
1.2 PHP文件上传处理
<?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));
// 检查文件是否是真实的图片
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;
}
}
// 检查文件是否已存在
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($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查是否没有错误,并且文件是否已上传
if ($uploadOk == 1) {
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.";
}
}
}
?>
二、实践技巧
2.1 文件权限
在服务器上对文件进行读写操作时,一定要检查文件权限。如果没有权限,将无法正常上传文件。可以使用以下命令检查和设置文件权限:
chmod 755 uploads/
2.2 错误处理
在处理文件上传时,可能会遇到各种错误。为了提高用户体验,建议在脚本中添加错误处理逻辑,并给出相应的提示信息。
2.3 文件重命名
为了避免文件名冲突,建议在上传文件时对文件名进行重命名。可以使用以下代码实现:
$target_file = $target_dir . uniqid() . "." . $imageFileType;
2.4 图片处理
// 获取图片信息
$image = getimagesize($target_file);
$width = $image[0];
$height = $image[1];
// 创建新的图片资源
$resize = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($target_file);
// 调整图片大小
imagecopyresampled($resize, $image, 0, 0, 0, 0, $width, $height, $width, $height);
// 保存新的图片
imagejpeg($resize, $target_file);