PHP check if the link is used as a page asset or directly accessed
I have a script image.php, which processes image files and returns the result. The link can look like this: https://example.com/image.php?id=123
, and it finds the corresponding file in the database and returns it to be used:
<img src='https://example.com/image.php?id=123' alt='' />
Is it possible for the image.php file to somehow distinguish the situation when it is used on a website as shown above and when the user clicks 'show image in new tab' or just inserts the link directly to the address bar?
Answers
Yes, it is possible for the image.php
script to distinguish between different scenarios based on how it is accessed. Here are a few approaches you can consider:
-
Referer Header: The
Referer
header in the HTTP request contains the URL of the referring page. When the image is loaded as part of a webpage, theReferer
header will typically contain the URL of that webpage. However, note that theReferer
header can be spoofed or blocked by privacy settings. -
Query Parameters: You can add additional query parameters to the URL when including the image in a webpage. For example, you could include
type=embedded
ortype=direct
as a query parameter in the URL. Theimage.php
script can then check for the presence of this parameter to determine how it is being accessed. -
HTTP Accept Header: The
Accept
header in the HTTP request specifies the media types that the client can understand. When the image is loaded as part of a webpage, theAccept
header will typically containtext/html
. If the image is accessed directly (e.g., opened in a new tab), theAccept
header may containimage/webp
orimage/png
, depending on the browser and image format. -
User-Agent Header: The
User-Agent
header in the HTTP request contains information about the client (e.g., browser, device). You can inspect theUser-Agent
header to determine if the request is coming from a browser or another type of client.
Here's an example of how you can implement the first approach using the Referer
header:
// Check if the Referer header is set
if (isset($_SERVER['HTTP_REFERER'])) {
// Referer header is set, so the image is being loaded as part of a webpage
// You can parse and analyze the Referer URL if needed
$refererUrl = $_SERVER['HTTP_REFERER'];
// Additional processing based on the Referer URL
} else {
// Referer header is not set, so the image is being accessed directly
// Additional processing for direct access
}
Keep in mind that relying solely on client-provided information like headers can be unreliable due to potential spoofing or blocking. Therefore, consider implementing multiple checks or combining different approaches for more robust detection.