What are the best practices for structuring PHP code to handle multiple pages within a single PHP file?
When handling multiple pages within a single PHP file, it is best practice to use conditional statements to determine which page is being accessed and then execute the corresponding code block. This can be achieved by using a parameter in the URL or a form submission to indicate the desired page. By organizing the code in this way, you can keep the logic for each page separate and maintain a clean and manageable code structure.
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
switch ($page) {
case 'home':
// Code for home page
break;
case 'about':
// Code for about page
break;
case 'contact':
// Code for contact page
break;
default:
// Code for default page or error handling
}
?>