Secure Page Switching in PHP with URL Parameters


Switching between different pages on a website is a common feature in PHP applications.

In this tutorial, we’ll walk you through how to safely switch pages using URL parameters.
We’ll also show you how to prevent security risks, like unauthorised file access, by using a whitelist of allowed pages.
By the end, you’ll have a simple and secure way to handle page navigation in PHP.

index.php
  1. <?php
  2. // Get the 'page' parameter from the URL, defaulting to 'main' if not set
  3. $page = isset($_GET['page']) ? $_GET['page'] : 'home';
  4.  
  5. // Whitelist of allowed pages to prevent unauthorised file inclusion
  6. $allowed_pages = [
  7. 'home' => 'home.php',
  8. 'login' => 'login.php',
  9. 'contact' => 'contact.php'
  10. ];
  11.  
  12. // Check if the requested page is in the whitelist
  13. if (array_key_exists($page, $allowed_pages)) {
  14. include($allowed_pages[$page]);
  15. } else {
  16. // Fallback to default page if the requested page is not allowed
  17. include('home.php');
  18. }
  19. ?>



A URL of index.php?page=contact will show the contents of contact.php
chrism's Avatar
Author:
Views:
2,434
Rating:
Posted on Saturday 21st December 2024 at 08:03 PM
DanielXP
DanielXP's Avatar
I've updated this to a more efficient and safer method of doing this.
Posted on Sunday 1st June 2008 at 03:12 AM
Adam981
Adam981's Avatar
Sorry for the double post. well i got a different switch PHP Navigation to work, so i'm guessing from looking at the code and what not that this wouldnt work for anyone, seeing that you might need a "GET" function.
Posted on Sunday 1st June 2008 at 02:09 AM
Adam981
Adam981's Avatar
Wow, i really cant make this work, when i go to link the page

example: "index.php?page=register"
it doesnt change the page and just includes main.php
Posted on Monday 7th April 2008 at 05:33 PM
Dalez
Dalez's Avatar
Hmm, i did this fine!

But when trying it with rmbs usersystem, when some of the pages use this, its messes up :(

And i dunno how to make it work :P
Posted on Monday 7th April 2008 at 03:14 PM
Dalez
Dalez's Avatar
Thanks, gonna try now!