PHP Dynamic Includes - Tutorials - in Obscuro
PHP Dynamic Includes - Tutorials - in Obscuro
com/tutorials/print/16/
<?php
$page = $_GET['page']; /* gets the variable $page */
if (!empty($page)) {
include($page);
} /* if $page has a value, include it */
else {
include('page1.php');
} /* otherwise, include the default page */
?>
You can name $page anything you want - $x, $y, $go...
Since obviously you didn't set the value for $page in any way, opening index.php will always display page1.php. How to change
this?
Make links: page 1, page 2, page 3. Each of them should state this:
1 of 3 3/15/19, 4:55 PM
PHP dynamic includes | tutorials | In obscuro http://inobscuro.com/tutorials/print/16/
The link index.php?page=page1.php doesn't look that great. If we could get rid of that .php on the tail it would be be$er.
Well, it's easy, if we know how to connect strings in PHP. And we do. (Have you read the Introduc:on to PHP (h$p://inobscuro.com
/tutorials/read/13/) ?)
Change all links to <a href="index.php?page=page1">page 1</a> (delete the .php at the end of the link). Then add the
following line to the code before the include funcBon:
$page .= '.php';
The line above is short for $page = $page . '.php'; The enBre code should then look like this:
<?php
$page = $_GET['page'];
if (!empty($page)) {
$page .= '.php';
include($page);
}
else {
include('page1.php');
}
?>
You're done! There is only something else we can do to make sure it includes only the files we want it to, a security patch if you
want to call it so. We will create an array of strings $pages containing filenames that are allowed to be included. If the page
defined by variable $page is not in the array, it will display the message: “Page not found. Return to index”.
<?php
$page = $_GET['page'];
$pages = array('page1', 'page2', 'page3');
if (!empty($page)) {
if(in_array($page,$pages)) {
$page .= '.php';
include($page);
}
else {
echo 'Page not found. Return to
<a href="index.php">index</a>';
}
}
else {
include('page1.php');
}
?>
So, when you add more pages to your website, you will also need to add them to the array $pages to make it work :)
What's great about this method is that any Bme you decide to change the layout, you will only need to change the file index.php
All other files remain exactly the same! :D
2 of 3 3/15/19, 4:55 PM
PHP dynamic includes | tutorials | In obscuro http://inobscuro.com/tutorials/print/16/
<a href="index.php?category=info&page=faq">FAQ</a>
<?php
$url = '';
if (!empty($_GET['category'])) {
$url .= $_GET['category'] . '/';
}
if (!empty($_GET['page'])) {
$url .= $_GET['page'] . '.php';
}
include $url;
?>
The above example works in cases when category (folder) is defined, and it works when it's not defined as well.
Hope this tutorial was helpful. Good luck!
3 of 3 3/15/19, 4:55 PM