English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have a particular website that I have built using a single main page with content include files that are inserted into the main page with include(). I have used a rather long switch command to decide which content file should be inserted. Basically as follows:

$page = $_GET['go'];
switch ($page) {
case "1": include("content/home.inc");
break;
case "2" include("content/about.inc");
break;
etc.... }

I currently have about 25 case statements, which seems very cluttered. It is also a pain to update the switch statements every time I add a page.

Is there an easier/less complicated way to do this?

Thanks!

2007-08-28 14:36:39 · 3 answers · asked by Tim K 1 in Computers & Internet Programming & Design

3 answers

Possibly. You can do something like this:

$pages = array('home', 'about', 'and_other_pages');
$page = (int) $_GET['go'];
$file = "content/{$pages[$page]}.inc";
if (file_exists($file)) {
include $file;
} else {
include 'content/notfound.inc';
}

This is similar to what Riff Almighty proposed above, but Riff Almighty's code is vulnerable to cross-site scripting.

2007-08-31 13:01:20 · answer #1 · answered by NC 7 · 1 0

You can use array variable:

$path=array('content/home.inc',
'content/about.inc',
'.......................',);
the home.inc is considered as the $path[0], the about.inc = $path[1] etc.

Then for the include, just write

include($path[$page]);

without any case of if statement
so whenever you want to update, just change the array

2007-08-28 21:52:40 · answer #2 · answered by Riff Almighty 3 · 0 0

Look into the Smarty templating engine, it's great for doing stuff like this.

http://smarty.php.net

Then your file would look like:



{$title}


{include file='page_header.tpl'}

{* body of template goes here, the $tpl_name variable
is replaced with a value eg 'contact.tpl'
*}
{include file="$tpl_name.tpl"}

{include file='page_footer.tpl'}

2007-08-28 21:54:46 · answer #3 · answered by Dirty Randy 6 · 0 0

fedest.com, questions and answers