Echo/print a jpg-image with php, for safety?

后端 未结 3 432
Happy的楠姐
Happy的楠姐 2021-01-06 02:53

Because of safety (check if user are logged in), I call a php-document when showing images.

...

...&l         


        
3条回答
  •  离开以前
    2021-01-06 03:01

    First of all, instead of reading the file with file_get_contents and, only then, echoing its content, you can use readfile : it will do both operations in one call -- which will probably be fastest and use less memory than :

    • load the full file in memory with file_get_only
    • and, only then, send that content to the outout


    Then, if you only want identified to have access to the images, you don't have much of a choice : if you indentification mecanism is based on PHP, you'll have to pass by PHP to restrict access on the file -- which, yes, will be a bit slower than if using Apache directly to serve the content.


    Also : here, you say :

    I hope the user never will know the direct url to the image

    Reading this, I suppose that your images can be accessed directly via Apache, bypassing your PHP script, if someone knows their URL ; security by obscurity is not good.

    A better solution, if you don't want your images to be served by Apache would be to put them in a directory from where Apache will not serve anything :

    • either a sub-directory of your document-root, protected by a .htaccess file containing "Deny from all"
    • or a directory that is not under your document-root, and, so, will never be served by Apache.

    Either way, this ensure only your scripts can access the files, and not Apache directly -- which means not a user bypassing the script.


    Another idea, about the performance problem, might be to indicate the browser that it can cache your images -- at least, if that makes a sense.

    For instance, you might be interested by HTTP-headers suchs as "Etag" and/or "Last-Modified".

提交回复
热议问题