Search code examples
phpimagerestriction

PHP: How to restrict the images returned by a php file based on users/groups?


Following an advice on this website I used an image.php file to return an image resource, as suggested here (linking to the images as files is not an option due to security restrictions).

How can I restrict the images that a certain user can 'get' from this image.php file?

I am using an OOP MVC architecture in my website. Upon connection, when index.php runs, many classes are loaded and instantiated thus the thread has variables indicating who the user is and what resources he can access.

This file image.php (returns an image) acts as a 'stand alone' script (accessed by an HTML src attribute from the client side), not loaded by the already-running thread, and (forgive me if I misunderstand it) has no variables to indicate who the user is and what he can access.

I could have image.php go through the same routine as index.php, loading and instantiating classes, but I think it would be a terrible waste of resources for a single image.

How can I restrict the images returned by image.php on user basis without creating an additional load on the server?

EDIT: I have observed on some websites that image.php is passes a long string GET variable, can that be a method?

If I explained myself in an unclear manner, please be patient and let me know, I'll try to clarify.


Solution

  • You need to identify the user somehow on image.php and that will depend on how you create the user session. If you are using PHP sessions you could just do:

    session_start();
    $username = $_SESSION['username'];
    // check permissions
    

    Most frameworks use adapters and wrappers to PHP session, on image.php just var_dump($_SESSION) and check if the information you need is there. Don't forget to call session_start.