How can you protect an images folder from being accessed directly or linked to by external sites using PHP?

To protect an images folder from being accessed directly or linked to by external sites using PHP, you can create a PHP script that checks if the request is coming from your own domain and then serves the image accordingly. This way, only requests originating from your website will be allowed to access the images.

<?php
// Check if the request is coming from your domain
$referer = $_SERVER['HTTP_REFERER'];

if (strpos($referer, 'yourdomain.com') === false) {
    // If request is not from your domain, deny access
    header('HTTP/1.0 403 Forbidden');
    exit;
}

// Serve the image if request is from your domain
$imagePath = 'path/to/your/image.jpg';
header('Content-Type: image/jpeg');
readfile($imagePath);