PHP redirect a la Javascript

So, I’ve been dabbling in PHP a bit and I needed to find out how to redirect in the middle of a page. I couldn’t find anything simple to achieve this so I wondered if it was possible to use echo a location.href in the midst of my PHP code. Turns out, it is!

The following snippet looks for a URL parameter named page. If no parameter was passed, the page will reload with a page parameter of page1:

if (isset($_GET[‘page’])) {
$pathToPage = sprintf(“%s%s.php”, ‘myfolder/’,$_GET[‘page’]);
} else {
echo ‘<script>location.href=”template.php?pg=page1″;</script>’ ;

Since it’s part of the example I should mention that sprintf is a fantastic substitution function that makes life a lot easier. In my example it is substituting the instances of %s with a folder name and a page name read from a URL parameter named page. For example, if the value of page was ‘page2’, the resulting string would be: ‘myfolder/page2.php’. Pretty slick!