Serve multiple pages from 1 PHP file?

So basically I struggle with the need to optimize my code for my project. Currently I have pages like add_company.php , view_company.php , edit_company.php .

What I would like to do is serve all the content from only one company.php PHP file. So to say company.php?action=view , company.php?action=edit , etc. Is this the only way to do this with massive if else expressions? That would make my company.php look like mega huge.

Or maybe even better, how can I serve all my pages just using index.php?

So what would be the best way to achieve this? I am not a php guru and I don’t have much experience with MVC or any other template.

Thanks.

+4
source share
5 answers

You can do company.php

 <?php $allowed = array('add', 'view', 'edit'); if ( ! isset($_GET['action'])) { die('missing param'); } $action = $_GET['action']; if ( ! in_array($action, $allowed)) { die('invalid'); } require $action . '_' . __FILE__; 

Quick and dirty, but it should work :) You can put this code into any file and it will work right away.

With a little change, you can make this your front controller with index.php .

+3
source

This is pretty simple stuff. It should look something like this:

 //index.php if (!isset($_GET['page'])) { require('index_contents.php'); } else if ($_GET['page'] == 'company') { if (!isset($_GET['action'])) { require('company_contents.php'); } else if ($_GET['action'] == 'edit') { require('edit_company.php'); } else if ($_GET['action'] == 'add') { require('add_company.php'); } else { require('company_contents.php'); } } else { require('index_contents.php'); } 
0
source

A very simple solution is to simply use include.

 if ($_GET["action"] == "view") { require("action_view.php"); } else if ... 

(of course, you can use the switch statement if you have many different types of pages)

Then action_view.php contains only the code for a specific page.

The best, but also more complex solutions will be an object-oriented approach (an abstract page class with a Factory template) or a direct mechanism for creating a frame and template.

0
source

You can use POST instead of GET with index.php:

 <?php require($_POST['action'] . ".php"); ?> 

This will hide the type of action from the user, acting as if it were one page. However, this may require the use of the form in your navigation, and not a direct link to "company.php? Action = edit".

0
source

I always prefer to use the switch statement for the $ _GET variable. His personal preference is to put all the logic related to one object (in this case the company) into one PHP file, because I usually deal with tons of entities. If you want an MVC model, this may not be what you are looking for. Only my 2 cents.

 // Common page header // Other stuff common in the pages $page_to_load = $_GET[view]; switch($page_to_load) { case 'view': //Logic to view or HTML for view break; case 'add': //Logic to add or HTML for add break; } // Common footer etc.. 
0
source

All Articles