PHP 是一种广泛使用的服务器端脚本语言,特别适用于 Web 开发。上传图片是 Web 应用程序中的常见功能,允许用户将图片文件从本地计算机上传到服务器。
以下是一个简单的 PHP 代码示例,用于处理单文件上传:
<?php
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$allowedExtensions = array("jpg", "jpeg", "png", "gif");
if (in_array($fileExtension, $allowedExtensions)) {
if ($fileSize < 2048) {
$newFileName = md5(date('YmdHis') . "_" . $fileName) . '.' . $fileExtension;
$dest_path = 'uploads/' . $newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)) {
echo "File is successfully uploaded.";
} else {
echo "There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.";
}
} else {
echo "File size is too big!";
}
} else {
echo "Only JPG, JPEG, PNG & GIF files are allowed.";
}
} else {
echo "There is some error in the file upload. Please check the following error.<br>";
echo "Error:" . $_FILES['file']['error'];
}
?>php.ini 文件中的 upload_max_filesize 和 post_max_size 设置,确保它们足够大。getimagesize() 函数来验证文件是否为图片。exif_imagetype() 函数来检查文件类型。move_uploaded_file() 函数来移动上传的文件,而不是直接使用 copy() 或 rename()。通过以上步骤,可以确保 PHP 中的图片上传功能既方便又安全。