Simple redirect (base64 escaped URL) in PHP

Let me start this off with a bit of background information.

David Grant runs a multitude of websites, and writes some great compact code. As a matter of fact, Rollator is based upon some of his ‘discarded’ code – although not all that much is left of it anymore.

I’ve been checking his QuickBlog website upon occasion since he’s made it public, and noticed yet another cute little thing he seems to have recently implemented (although I’m not sure if he’s doing it manually, or with regex to replace hrefs). If you look at his links, they are all pointing to his index with an innocuous ‘go’ command, which has a base64 encoded hash which is the url to redirect to.

I’ve been considering doing similar things with my own site, mostly just to do it, and to have some feedback on which of my articles people are following, so I might curtail my subjects to a wider, more global audience. I’ve toyed with the thought of pushing everything through my URL shortener (in theory, had I a small domain name) tool – but that’s rather wasteful, and un-ncessary.

Anyhow, here’s a quick 10 second reimplementation of David’s ‘go’, as I see it, with a optional second variable available to redirect to a specific page if hashing fails. Note that if there is no redirect clause, if the redirect fails, it just falls through, because I’ve set no redirectIfFailURL. (I’ve not tested for this ability on David’s site, I consider that to be rude):

function goURL ($urlHash=””, $redirectIfFailURL=””) { if(base64_decode($urlHash)) { header (“location: ” . base64_decode($urlHash)); } else { if($redirectIfFailURL) header (“location: $redirectIfFailURL”); } }

Of course, you’d want to trap for this ‘go’ variable in the index – then, if it is found, pass to goURL();, such as:

goURL($safeEscapedURLHash); or even: goURL($safeEscapedURLHash, $myHomePageURL);

Pretty simple, and yet, quite useful!

[Edit: Append] I’ve changed my URL redirect link above to link to my diary entry for information on how to use my redirect service, rather than a direct link to the undocumented service, itself!