What are the best practices for blocking specific referrers in PHP to prevent unwanted traffic?

Unwanted traffic from specific referrers can be blocked in PHP by checking the HTTP referer header and redirecting or displaying an error message if the referrer matches the blocked list. This can help prevent spam, bots, or malicious traffic from accessing your site.

<?php
$blocked_referrers = array("example.com", "spamdomain.com");

if (isset($_SERVER['HTTP_REFERER'])) {
    $referer = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    
    if (in_array($referer, $blocked_referrers)) {
        // Redirect or display an error message
        header("Location: https://yourwebsite.com/error-page.php");
        exit;
    }
}
?>