Search code examples
phpimageuploadstoredocument-root

PHP where to save user uploaded image files


currently i am saving user uploaded image files as follows:

public_html/img/user/$category/$username/$imagename

however, is this bad practice? Why is it bad to store in document root and where would a better place to store the files be?

i filter extensions as follows:

    // Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
    // This is an array that holds all the valid image MIME types
    $valid_types = array("image/jpg", "image/JPG", "image/jpeg", "image/bmp", "image/gif", "image/png");

    if (in_array($file['type'], $valid_types))
        return 1;
    return 0;
}

Solution

  • Contrary to what some believe is bad practice, the location itself is not the problem; but you have to take care of a few things:

    • Filter by extensions; accept a few image formats (.jpg, .gif, .png) only and reject the rest; definitely don't accept .php extension

    • Don't trust the mime-type sent by the browsers to determine if an image is valid. Use getimagesize() to do this yourself; this can be fooled by hiding a PHP script inside an image, but that's why we have one more important step.

    • Important - Make sure that images are NOT served with the PHP engine; some images can be crafted in a way that it looks like an image but hides a script inside. Use the web server's configuration for this.

    • Other issues you need to be aware about when you're handling uploads

    See also: Secure User Image Upload Capabilities in PHP

    Btw, to test if the PHP engine is not being used to serve images, make sure the expose_php is On (you can tell from a phpinfo() page. Then download an image with your browser, inspect the response headers and check whether you see the X-Powered-By header; if it's not there, you should be safe.