Forum Moderators: coopster

Message Too Old, No Replies

using switch case to show different content for diff ID

         

alahamdan

7:22 pm on Jan 15, 2012 (gmt 0)

10+ Year Member



Hello,

I'm very new to php and i need some help please.

I have few related pages, where each of them is a separated php file, now im thinking of making them all work as index.php?page=ID.

Searching for a while i found a code do the trick like this:


<?php
//Main funciton for the Page layout
function layout($page_id) {
switch($page_id) {
default: //Default, ie when the page_id does not match with predefined cases

case '': //When it is null
case 'page1':
echo '<h2>page 1 content</h2>';
break;
case 'page2':
echo '<h2>page2 content</h2>';
}
}
?>

//then i call the content using
$page_id = $_GET['page']; //Get the request URL
layout($page_id); //Call the function with the argument


Ok i could get this work, but i have 2 questions pls:

1- how can i 301 redirect the default case so any request to non-available url be redirected to main page for example? (so i make sure wont get duplicate content issue).

2- I'm planning to do this for about 20 pages, changing 3 blocks in each page, there is some way to sort each same kind block in a file and call that block from the file? (i know i can include a whole file, how to get part of a file?).

Many thanks in advance.

enigma1

4:25 pm on Jan 17, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could do something simpler and use an integer for the page ID.


$page_id = isset($_GET['page'])?(int)$_GET['page']:0;
$template_file = 'templates/page-' . $page_id . '.tpl';
if( is_file($template_file) ) {
require($template_file);
// Do other stuff if necessary
} else {
header("HTTP/1.1 301");
header("location: http://www.example.com"); // Home page
}
exit();

So the script will work for any page when there is a page-n.tpl file present, otherwise it will redirect to the home page. The various page-n files could use some common code or html also to minimize maintenance.