PHP check if the link is used as a page asset or directly access

ghz 7months ago ⋅ 45 views

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:

  1. 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, the Referer header will typically contain the URL of that webpage. However, note that the Referer header can be spoofed or blocked by privacy settings.

  2. 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 or type=direct as a query parameter in the URL. The image.php script can then check for the presence of this parameter to determine how it is being accessed.

  3. 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, the Accept header will typically contain text/html. If the image is accessed directly (e.g., opened in a new tab), the Accept header may contain image/webp or image/png, depending on the browser and image format.

  4. User-Agent Header: The User-Agent header in the HTTP request contains information about the client (e.g., browser, device). You can inspect the User-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.