Echo / print jpg image with php, for security?

Due to security (check if the user is registered), I invoke a php document when displaying images.

<html>...
<img src="showImage.php?id=455" />
...</html>


showImage.php:
<?php...

if($_SESSION['user']){
    //Get the src to the image
    $_GET[$id] = mysql_real_escape_string($_GET['id']); 
    $result = mysql_query("
        SELECT src
        FROM Media 
        WHERE id = '".$_GET['id']."'
        ");
    $data = mysql_fetch_assoc($resultat);

    // Output the image
    header('Content-Type: image/jpeg');
    echo(file_get_contents("media/".$data['src']));
}

...?>

At the same time, I hope that the user will never know the direct URL of the image, and when trying to show the image, the user must log in.

I am not sure if this is the best way. Is there an easier / better way to do this and it is safe. When the script echoes, it is a little slower.

  • I want the image to be safe (only registered user should have access to the image)
  • I want the image displayed as quickly as possible

Looking forward to all your expert advice.

+5
source share
3

, file_get_contents , , , readfile: - , , , :

  • file_get_only
  • outout


, , , : mecanism PHP, PHP, - , , , Apache .


: :

, URL-

, , Apache, PHP script, - URL; .

, , Apache, , , Apache :

  • , .htaccess, "Deny from all"
  • , , Apache.

, , , Apache, , script.


, , , , - , .

, HTTP-, "Etag" / "Last-Modified".

+10

, , , , . , , , PHP ( ).

<?php

if($_SESSION['user']){

    $result = mysql_query("SELECT src FROM Media WHERE id = '"
    . mysql_real_escape_string($_GET['id']) ."'");

    $data = mysql_fetch_assoc($resultat);

    // Output the image
    header('Content-Type: image/jpeg');
    readfile("media/". $data['src']));
}
+2

Pascal MARTIN is correct, which readfileessentially matches echoand file_get_contents. I doubt there is any significant difference in performance, but it’s clearer to use readfile.

If you allow users to view images, place them outside your web directory. Using readfile, you can capture the file from another directory. Thus, they could not access it, even if they guessed the URL.

0
source

All Articles