Jump to content

Recommended Posts

Hello everyone. This is my first post to the forums so first I would like to say hello to everyone.

The question I have is this:

I am designing a website and I want to incorporate a system that will look at the URL and decide which include to use.

I have everything working using some code like this:

<?php
$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');

if($page == "index") {
include('includes/index.inc');
}
elseif($page == "someOtherPage") {
include('includes/someOtherPage.inc');
}
else {
echo 'blah blah blah';
?>

 

As you can see this can get redundant really fast.

What I want to do is store all of the page names in an array and loop through them, including the page that matches the conditional, But I cant figure out how to get it to work.

 

Any suggestions?

 

Thanks in advance :)

Link to comment
https://forums.phpfreaks.com/topic/115859-solved-question-about-looping/
Share on other sites

Try this (some editing may need to be done still, not tested):

$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');

$myArray = ('index','someOtherPage','anotherPage');

foreach($myArray as $pa){
     if($page == $pa) {
          include('includes/'.$pa.'.inc');
          break;
     }else{
          echo 'Page Not Found';
     }
}

I wouldn't do that because you'd get "Page not found" every time you iterated before the page was found.  I'd personally do:

 

 

$pages = array('home', 'contact', 'aboutus', 'something);

if (in_array(strtolower($_GET['page']), $pages)) {

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

}

better to use in_array

 

//               page name          page path
$pages = array( 'index'         => 'includes/index.inc',
               'someotherpage' => 'includes/someotherpage.inc'
             );

if(in_array($requested_page_var, $pages))
{
   include $pages[$requested_page_var];
}

this could be a way so you don't have to create an array:

 

$path = 'includes/';

$page = $_SERVER['PHP_SELF'];
$page = basename($page);
$page = basename($page, '.php');

if(is_file($path . $page)){
include $path . $page;
}else{
echo 'Invalid File';
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.