使用PHP验证头像图像

时间:2015-01-04 18:02:27

标签: php image validation file-upload

我在MySQL数据库中有一个名为mediumblob的照片的列,它可以是NULL

这应该代表显示在Web应用程序右上角的员工的一张小照片。

新员工通过表单插入MySQL数据库。

<form action="insert" method="post" enctype="multipart/form-data">
   ...
   <label for="photo">Photo</label>
   <input type="file" name="photo">
   ...
</form>

照片的验证如下:

  1. 可以卸载(表单中不会提供照片)

    否则,如果提供了一些照片

  2. 应为图像类型
  3. 图像尺寸应适合此目的
  4. 图像的尺寸应适合此目的
  5. 以下是我的验证码的概要。 我已经创建了一些验证条件(1和2)。那些好吗? 并且不知道如何创造条件3和4。

    $file = $_FILES['photo']['tmp_name']
    if (!isset($file))
    {
        $image = ""; // 1), empty string will be inserted into the database
    }
    else {
        $image = addslashes(file_get_contents($_FILES['photo']['tmp_name']));
        $image_size = getimagesize($_FILES['photo']['tmp_name']);
    
        if ($image_size == FALSE) { 
          // 2) not an image file
          // display the form again with error message
        }
    
        // checking 3)
        // checking 4)
    }
    

6 个答案:

答案 0 :(得分:2)

  

对于条件3,你可以使用:

$filesize = filesize($filename);

u get size of the file in bytes.


For condition 4 u can use:

list($width, $height) = getimagesize($_FILES['photo']['tmp_name']);

where $width and $height is the dimension of image.

答案 1 :(得分:2)

以下是一些包含在代码中的有用提示:

$upload_error = isset( $_FILES['photo']['error'] ) ? $_FILES['photo']['error'] : UPLOAD_ERR_NO_FILE;
if ($upload_error == UPLOAD_ERR_NO_FILE) {
    // 1) No file uploaded
    $image = null; // I changed the empty string into a null, to avoid the mediumblob allocating space for the empty string
} elseif ($upload_error) {
    // 5) You forgot to check if the file upload failed
    switch ($upload_error) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            $message = "file_too_big";
            break;
        case UPLOAD_ERR_PARTIAL:
            $message = "upload_not_complete";
            break;
        case UPLOAD_ERR_EXTENSION:
            $message = "bad_file_extension";
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
        case UPLOAD_ERR_CANT_WRITE:
            $message = "internal_upload_error";
            break;
        default:
            $message = "unknown_upload_error";
            break;
    } 
    header("Location: form.php?error=$message"); // Load form again and show error
    exit;
} else {
    $file = $_FILES['photo']['tmp_name'];
    $file_size = $_FILES['photo']['size'];
    if ($file_size > 5242880) { // 5 Megabyte for example, but always less than 16 Megabytes, because you use mediumblob
        // 3) The image size is not suitable for this purpose
        header("Location: form.php?error=file_too_big"); // Load form again and show error
        exit;
    }
    $image_size = getimagesize($file);
    if ($image_size) {
        $width = $image_size[0];
        $height = $image_size[1];
        if ($width < 100 || $width > 1000 || $height < 100 || $height > 1000) {
            // 4) Image dimensions are not suitable. Width/height are not between 100 and 1000 pixels
            header("Location: form.php?error=dimensions_not_ok"); // Load form again and show error
            exit;
        }
    } else {
        // 2) Not an image type
        header("Location: form.php?error=not_an_image"); // Load form again and show error
        exit;
    }
    $image = file_get_contents($file);
}
// now escape $image and save it to the database
// But I suggest you not use addslashes() to escape binary data
// Use parameterized queries / mysqli_real_escape_string() / mysql_real_escape_string() instead

答案 2 :(得分:1)

Best way to determine if a file is empty (php)?用于第1点 第二点根本不完整(不安全):
例如。添加扩展程序检查:PHP check file extension
针对第2点的更多安全提示:http://nullcandy.com/php-image-upload-security-how-not-to-do-it/
第3点和第4点可以用getimagesize()filesize()覆盖 Get image dimensions
http://php.net/manual/en/function.filesize.php

答案 3 :(得分:1)

您的代码没问题,只需添加以下行即可满足您的所有要求:

$image="";
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] < 1){
    $file = $_FILES['photo']['tmp_name'];
    $imageInfo = getimagesize($file);
    if(is_array($imageInfo)){
         if($imageInfo[0]>30 && $imageInfo[0]<257 && $imageInfo[1]>30 && $imageInfo[1]<257){
           //$imageInfo[0] is width and $imageInfo[1] is height, you can set limit according to your need. I set it to MIN: 31*31 AND MAX 256*256
           // if you want square image then add " && $imageInfo[0]=$imageInfo[1]" in above-if-clause

              $imageSize=filesize($file); //returns bytes in integer
              if($imageSize> 250 && $imageSize<20481) // image size should be less then 20kb
                  $image = addslashes(file_get_contents($file));
              else echo "Image file should not grater then 20 KB.";
         }
         else echo "Image dimension(width*height) should be 31*31 to 256*256.";
    }
    else echo "Wrong file. Upload a Image file.";
}
else echo "No file uploaded or Error in file uploaded.";

if(trim($image)==""){
   //display form again
}

答案 4 :(得分:1)

      $userfile_name = $_FILES['image']['name'];
         $userfile_tmp = $_FILES['image']['tmp_name'];
         $userfile_size = $_FILES['image']['size'];
         $filename = basename($_FILES['image']['name']);
         $allowedExts = array("gif", "jpeg", "jpg", "png");
         $extension = end(explode(".", $_FILES["image"]["name"]));
         if(($userfile_size / 1024) < 4096){
             if (isset($_FILES['image']['name']) && !empty($_FILES["image"]) && ($_FILES['image'] ['error'] == 0) && ($userfile_size / 1024 < 4096 ) && (($_FILES["image"]["type"] == "image/gif")
        || ($_FILES["image"]["type"] == "image/jpeg")
        || ($_FILES["image"]["type"] == "image/jpg")
        || ($_FILES["image"]["type"] == "image/pjpeg")
        || ($_FILES["image"]["type"] == "image/x-png")
        || ($_FILES["image"]["type"] == "image/png")) && in_array($extension, $allowedExts)) {
                        //Everything is ok, so we can upload the image.
        }else{
echo "Error in file Upload";
}
        }else{
    echo 'Oops!  Your file\'s size is to large.';
    }

对于第4点,您需要在实际上传发生之前在客户端上执行的操作。 使用(服务器端)php,您只能在文件上传后检查维度

答案 5 :(得分:1)

您可以使用以下PHP库: https://github.com/codeguy/Upload