What are some common methods to prevent image hotlinking and protect against traffic costs in PHP?

Image hotlinking is when another website directly links to images on your server, causing increased bandwidth costs for you. To prevent this, you can check the HTTP referer header to ensure the request is coming from your own website. If not, you can redirect the request to a default image or display an error message.

<?php
// Check if the request is a hotlink
if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
    $referer = parse_url($_SERVER['HTTP_REFERER']);
    if ($referer['host'] != 'yourwebsite.com') {
        // Redirect to a default image or display an error message
        header('Location: default_image.jpg');
        exit;
    }
}