URL Rewriting for PHP script on an image URL

I built an image randomizer so that when I open a .php file in a URL that it displays the image with readfile($randomImage);. This works locally but when I upload it to the server it gets blocked by the firewall since we do not want to be able to load URLs like

https://www.example.com/wp-content/themes/THEME/randomImage.php

I want to load a .php script on a .jpg file. What needs to happen is that when I use the URL (for instance)

https://www.example.com/image.jpg

and when I load this image that it runs a PHP file like

https://www.example.com/randomizer.php

In other words, I want WordPress to think that it is loading a URL ending with .jpg but opens a .php file

Is this something that is realizable?

Topic template-redirect rewrite-rules mod-rewrite url-rewriting Wordpress

Category Web


I created a function named randomImage() that simply takes a random image from an array, this function gets called in with the function below:

function imageRedirect(){
// Get the page name from the URL
$page = $_SERVER["REQUEST_URI"];

// Make sure debug mode is disabled since the deprecation errors will ruin the photo content
if (WP_DEBUG) throw new Exception('Due to depreciation errors this photo can only be rendered with debug mode disabled!');

// If we're on the random image page
if ($page == RANDOM_IMAGE_URL) {

    // Fetch a random image and return the data
    $image = randomImage();

    header("Content-Type: image/jpeg");
    header("Content-Length: " . filesize($image));
    readfile($image);

    exit;
}
}

Try the following at the top of the .htaccess file, before the existing WordPress directives:

# Internally rewrite "/image.jpg" to "/randomizer.php"
RewriteRule ^image\.jpg$ randomizer.php [L]

This uses mod_rewrite to rewrite the URL. There is no need to repeat the RewriteEngine On directive (that occurs later in the file).

Any request for /image.jpg (in the document root) is internally/silently rewritten to your /randomizer.php PHP script (also in the document root - assuming that is where your .htaccess file is located, or where the RewriteBase directive points to).

I have a weird request maybe

This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL random-image.jpg or something similar maybe a good idea.

This is actually pretty much identical to a question I answered yesterday on StackOverflow: https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.