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;
}
}
Related Questions
- What is the best way to display large amounts of data from a database in PHP without overwhelming the user with too much information at once?
- What are the best practices for handling session variables in PHP to avoid security vulnerabilities?
- How can the use of Object-Oriented Programming (OOP) in MySQLi improve the efficiency and security of PHP scripts compared to the procedural approach?