What are the implications of using PHP scripts to prevent direct access to user images via direct links?

When user images are directly accessible via URLs, it can lead to security risks such as unauthorized access and hotlinking. To prevent this, you can use PHP scripts to restrict direct access to the images by checking if the request is coming from a valid source.

<?php
// Check if the request is coming from a valid source
if (!empty($_SERVER['HTTP_REFERER'])) {
    $referer = parse_url($_SERVER['HTTP_REFERER']);
    if ($referer['host'] == 'yourwebsite.com') {
        // Serve the image
        $imagePath = 'path/to/your/image.jpg';
        header('Content-Type: image/jpeg');
        readfile($imagePath);
        exit;
    }
}

// If the request is not valid, show an error image or redirect
$errorImagePath = 'path/to/error/image.jpg';
header('Content-Type: image/jpeg');
readfile($errorImagePath);
exit;
?>