简体   繁体   中英

What is the most secure method to upload image file to server with PHP?

I know this topic is widely talked about. I've done my research, and decided to store image files onto the server instead of the DB as a blob file. The problem that I am having is trying to figure out the best way to upload the file, store it in a designated folder then storing the destination in the db..say../img/something.jpg - I've tried looking through many resources but most of them are missing some important steps in the process.

Problems:

  1. Finding a secure way for uploading the img file
  2. Limiting the file
  3. size Uploading the image to a destination file
  4. Storing the destination file as a text in the DB

I'm using PHP and MySQL.

Dunno what all your points about, but what you really have to be concerned with is

  • check for the file extension.
    extract it from the filename and compare with allowed ones.
    also it would be good to check filename to have only one dot, or at least it doesn't have a name like name.html.jpg , due to some odd Apache behavior.

  • check for the file contents. the best way would be to create a brand new image out of the uploaded one.

  • take usual precautions while working with DB.

Here you go, this covers the basic ideas of what you want to do:

<?php
    $allowedTypes = array("image/jpg", "image/jpeg", "image/png");
    $maxSize = 3 * 1024 * 1024; // 3Mb

    $fileType = $_FILES["file"]["type"];
    $fileSize = $_FILES["file"]["size"];

    // check if there was an error
    if ($_FILES["file"]["error"] > 0)
    {
        die($_FILES["file"]["error"]);
    }

    // check if the filetype is valid
    if (!in_array($fileType, $allowedTypes))
    {
        die("Invalid file type: $fileType");
    }

    // check if the size doesn't exceed the limitations
    if ($fileSize > $maxSize)
    {
        die("The file was too big: $fileSize");
    }

    $name = $_FILES["file"]["name"];
    $tmpfile = $_FILES["file"]["tmp_name"];

    // check if the filename is valid
    if (preg_match("/[\w-]+\.(jpg|jpeg|png)$/", $name) != 1)
    {
        die("Invalid file name: $name");
    }

    // create unique name if needed

    $path = "/var/www/images/" . $name;

    move_uploaded_file($tmpfile, $path);

    // add the filepath to mysql
    mysql_connect("localhost", "username", "password");
    mysql_select_db("imagedb");
    mysql_query("INSERT INTO images (Location, Size) VALUES ('$path', '$size');");
?>

This is meant to show how it could be done.

read this

personally I'd use imgur which is used here on stackexchange websites

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM