PHP上传图片是指通过PHP脚本处理客户端上传的图片文件。这通常涉及到文件上传表单、服务器端的文件处理和存储。
以下是一个简单的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));
$allowedFileExtensions = array('jpg', 'jpeg', 'png', 'gif');
if (in_array($fileExtension, $allowedFileExtensions)) {
if ($fileSize < 2000000) { // 2MB
$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 exceeding the limit of 2MB.';
}
} 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'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file" id="file">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
php.ini
文件中的upload_max_filesize
和post_max_size
设置,确保它们足够大。getimagesize()
函数来验证文件是否为图片。move_uploaded_file()
函数来移动文件,而不是直接复制。通过以上步骤,你可以实现一个基本的PHP图片上传功能,并确保其安全性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云