1

目前我正在保存用户上传的图像文件,如下所示:

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

但是,这是不好的做法吗?为什么存储在文档根目录中是不好的,在哪里存储文件更好?

我过滤扩展如下:

    // 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;
}
4

2 回答 2

2

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.

于 2012-10-06T15:45:21.663 回答
1

Its better to keep publicly visible images in document root. But store only the images you want to show. Not the other one. And make sure these are image files as there are some gotchas.

I have a website where user stores image. But I keep the file name, category, username, imagename into database and the image files in a single directory.

于 2012-10-06T15:43:34.563 回答