如何使用 PHP 上传图像

How do I upload an image using PHP?

本文关键字:图像 PHP 何使用      更新时间:2023-09-26

如何上传图像并将其存储到 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> 

你的逻辑中有多个错误。

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 在可以存储的最大数据量方面自然受到限制。您不应该能够最多存储超过几千字节。由于您已将上传大小限制设置为 500k,因此如果您确实将 500k 存储到 1-2k cookie 中,您最终会得到损坏/截断的图像。