Page 1 of 1

Including

Posted: Fri Jan 30, 2004 11:46 am
by pac604
<?php
// index.php.
if (isset($_GET['id'])) {
switch($_GET['id']) {
case 0:
echo 'Welcome to my homepage!';
break;
case 1:
echo 'My name is Foo';
break;
default:
echo 'Nope, no such page here...';
}
}
?>
<br />
<a href="index.php?id=0">Homepage</a> | <a href="index.php?id=1">I am...</a>
Instead of having 'Welcome to my homepage!' for the echo 0, is their a way to just include it like having

<? include("Homepage.php") ?>

Posted: Fri Jan 30, 2004 11:52 am
by markl999
case 0:
require_once 'Homepage.php';
break;

Though i wouldn't use a switch() like that as it can become cumbersome with a large amount of possible pages that can be included... case 44: etc..etc. ;)

Posted: Fri Jan 30, 2004 12:22 pm
by pac604
Would you be able to do a different format then? I assume you know what concept I would wan't to do. So yea.. Is their any other way? I remember there is, much simpler. No need for the other codes.

Posted: Fri Jan 30, 2004 12:31 pm
by markl999
Well, there's a few ways to do it, but one way is to pass ?page=home for example in the url, then use something like :

Code: Select all

<?php
//array of allowed pages we can request
$allowed = array(
  'home', 'login', 'logout', 'info'
);

if(empty($_GET['page'])){
  $_GET['page'] = 'home'; //set the default page to view if non passed in the url
}
if(file_exists($_GET['page'].'.php') && in_array($_GET['page'], $allowed)){ //check the file exists and it is allowed
  require_once $_GET['page'].'.php';
} else {
  echo 'Invalid page request.'; //otherwise a bad page was requested
}

?>
This way you only have to add new pages to the $allowed array and the code should take care of itself.

Posted: Fri Jan 30, 2004 12:32 pm
by pac604
That confused me, but thanks anyways. I'll read some more tutorials to understand both of these coding. Thanks

Posted: Fri Jan 30, 2004 12:32 pm
by phpcoder
include("filename");

Posted: Fri Jan 30, 2004 12:48 pm
by John Cartwright
Let me explain a bit furthur

Code: Select all

<?php

//array of allowed pages we can request 
$allowed = array( 
  'home', 'login', 'logout', 'info' 
); 

if(empty($_GET['page'])){ 
  $_GET['page'] = 'home'; //set the default page to view if non passed in the url 
} 
if(file_exists($_GET['page'].'.php') && in_array($_GET['page'], $allowed)){ //check the file exists and it is allowed 
  require_once $_GET['page'].'.php'; 
} else { 
  echo 'Invalid page request.'; //otherwise something a bad page was requested 
} 


?>

What he said is you only have to change 1 line to add/delete pages which is

Code: Select all

<?php$allowed = array( 
  'home', 'login', 'logout', 'info' //add 'newpages'
); 

?>
Instead of having to create a new <? include ("filename"); ?> every time you want to add/remove a page.

Posted: Fri Jan 30, 2004 12:53 pm
by markl999
Thanks Phenom, i really need to improve my commenting skills ;)

Posted: Fri Jan 30, 2004 12:56 pm
by John Cartwright
:D