Multiple pages in one file
You can nest pages inside one PHP file using superglobals. The gist of it is you use the $_GET
to collect the variable of your choosing from the URL, which is appended to the end after a question mark. I call that variable p
here, but you can use whatever you want as long as the URL and PHP are consistent. (For example, if you want to access pages using the variable item
, you would need to have all your links point to yourfile.php?item=youritem
and $_GET['item']
.
One way to use this is to just nest stuff into your page directly using a switch command for an easy 1-file page:
<?php
$cmd = $_GET['p'];
switch ($cmd) {
case "page1": ?>
<!-- HTML FOR PAGE 1 HERE -->
<?php
break;
case "page2": ?>
<!-- HTML FOR PAGE 2 HERE -->
<?php
break;
}
?>
You can also store the content of each subpage in its own PHP file. When you name your files, you'll want to name them with the name you want to appear in your link. For instance, the file this page is being pulled from is called pages.php
. If you want your files to go in another directory, you can concatenate the folder into the filename
variable like $filename = "directory/".$cmd.".php";
.
<?php
$cmd = $_GET['p'];
$filename = $cmd.".php";
@include($filename);
?>
If you'd like a subpage to be displayed by default, you can put in if ($cmd=="") { $cmd = "home"; }
between the first two lines of code. home
should be changed to whichever file you want displayed.
Bonus content: Rewrite rules
You can make your one-page website even better using rewrite rules! Pop the following into your .htaccess file:
RewriteEngine on
RewriteRule ^([A-Za-z0-9\-]+)$ index.php?p=$1
Now you can link to pages like yourwebsite.com/page
instead of yourwebsite.com/index.php?p=page
. Change the filename to whatever you're using. You can also stick a directory into your URL.