Loko
Loko

Reputation: 6679

Difference between including everything on index and showing all different pages?

As I am learning about including pages on the index instead of showing the pages itself, I have a hard time with it. So I was wondering something.

Is there any difference between using something like this to switch to show different pages on index.php:

switch($page) {
case 'page1':
    $pagefile='page1';
    break;
case 'page2':
    $pagefile='page2';
    break;
case 'page3':
    $pagefile='page3';
    break;
case 'page4':
    $pagefile='page4';
    break;
default:
    $pagefile='home';
}


require_once(''.$pagefile.'.php');

and just showing the php files itself? As in functionality or security etc?

Upvotes: 0

Views: 122

Answers (3)

Robert
Robert

Reputation: 2824

U can use it for security i mean for example UR index.php be like this

include($_GET['page']."sec.php");

so the client won't see any page name only index.php?page=example and there are page name examplesec.php at UR folder so the client don't know the name of UR pages only see what ?page=the_page_name and U can change sec by and thing UR name or zzz

  • index.php will include another things at page like header , footer , side bar ... ect that will be at all pages

and U should use include_once so if there are any problem this will stop it

and for the pages is important use require_once so if the page not found the script will stop

Upvotes: 1

Loïc
Loïc

Reputation: 11943

Doing like this allows you to include some other thing in the same page and not have to repeat it on every page.

Let's say you have an header, a menu, your page, and the footer. Using this method you can do this :

<?php

$whiteList = array('index', 'page1', 'page2');

$page = in_array($_GET['page'], $whiteList) ? $_GET['page'] : 'index';

include('header.html');
include('menu.html');
include($page.'.php');
include('footer.html')

?>

EDIT : It's a very good thing to have an entry point to your application.

Let's say tomorrow you want to know how many total pages have been viewed, you can just add a counter in your index.php script (without repeating it in every other pages).

EDIT 2 : Note that the above code won't work everytime (there might be some error), but I won't spoil you the fun of finding out why. ;-)

Upvotes: 1

Roberto Arosemena
Roberto Arosemena

Reputation: 1140

Try it with this, it is smart to check the name because that way you protect sensitive files

if(in_array($page, ['page1', 'page2', 'page3', 'page4'])) {
    $pagefile = $page;
} else {
    $pagefile = 'home';
}

include($pagefile.'.php');

Upvotes: 0

Related Questions