Skip to content
PHP Logo

Are there best practices for using PHP to safeguard images on a website?

To safeguard images on a website using PHP, it is important to prevent direct access to the image files by users. One common approach is to store the images outside of the web root directory and use PHP to serve the images to users. This way, the images are only accessible through controlled PHP scripts, allowing you to implement security measures such as user authentication or access control.

php
<?php
// Check if the user is authenticated before serving the image
if (isset($_SESSION['user_authenticated'])) {
    $imagePath = '/path/to/image.jpg';
    
    // Output the image with appropriate headers
    header('Content-Type: image/jpeg');
    readfile($imagePath);
} else {
    // Redirect or show an error message if the user is not authenticated
    header('Location: /login.php');
}
?>