如何上传图片并将其存储到Cookie中?我希望能够上传一个有限制的图像,例如文件大小限制。
这是我的PHP代码:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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.";
}
}
?>
在此代码中是上传具有限制的文件的功能。
这是我的HTML代码:
<!DOCTYPE html>
<html>
<head>
<link href="bitnami.css" media="all" rel="Stylesheet" type="text/css" />
<link href="test.php"/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
答案 0 :(得分:4)
您的逻辑中存在多个错误。
1)您永远不会检查是否实际执行了上传。您只需开始处理['tmp_name']
而不检查它是否确实存在。处理上传的第一次操作必须检查错误:
if ($_FILES["fileToUpload"]['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileToUpload']['error']);
}
2)您正在根据文件扩展名检查文件类型。没有人说用户无法ren nastyvirus.exe cutekittens.jpg
并通过您的文件检查。您之后已经在使用getimagesize()
,因此扩展程序检查毫无意义:
$info = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($info === false) {
die("Not an image at all");
}
if (($info[2] != IMGTYPE_GIF) && ($info[2] != IMGTYPE_JPG) && ($info[2] != IMGTYPE_PNG)) {
die("Not a gif/jpg/png");
}
if (($info[0] > $maximum_width) || ($info[1] > $maximum_height)) {
die("Too tall/wide");
}
然后,在那之后 - 为什么要将它存储在cookie中? Cookie自然受限于可存储的最大数据量。您最多只能存储超过几千字节的内容。由于您已将上传大小限制设置为500k,因此如果您将500k存储到该1-2k cookie中,则最终会出现损坏/截断的图像。