I've written a simple php page that when you click on one of the links it includes a different php file, thereby changing the content. Below is the code I have so far, the only problem is that each time you click on a link, the URL changes to index.php?page=page1, which doesn't look very good.
<html>
<head>
<title> PHP Includes </title>
</head>
<body>
<h1> This is the home page </h1>
<ul>
<li><a href="includes.php?page=page1">Page1</a> </li>
<li><a href="includes.php?page=page2">Page2</a></li>
<li><a href="includes.php?page=page3">Page3</a></li>
</ul>
</body>
</html>
<div style='width:300px; height: 200px; border: 1px solid #000;'>
<?php
error_reporting(E_ALL ^ E_NOTICE);
$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
<a href="includes.php">home</a>';
}
}
else {
include('page1.php');
}
?>
</div>
I was wondering if there was a way to do the same thing (just change the content), without changing the URL in the address bar?
PHP is reloading its own page with a reference to the content to be added. The $_GET method is the natural way to do this, but there are two other options which spring to mind.
1) Use a session variable to reference the page to be loaded. 2) Use AJAX so that the page is never actually reloaded. Instead, you load the new content into the page via AJAX.
If you want to go the session variable route, then something like this will do it.
<?php
session_start();
if($_GET['page'])
{
// set session variable
$_SESSION['page'] = $_GET['page'];
// redirect to hide URL change
header('Location: includes.php');
}
?>
<html>
<head>
<title> PHP Includes </title>
</head>
<body>
<h1> This is the home page </h1>
<ul>
<li><a href="includes.php?page=page1">Page1</a> </li>
<li><a href="includes.php?page=page2">Page2</a></li>
<li><a href="includes.php?page=page3">Page3</a></li>
</ul>
</body>
</html>
<div style='width:300px; height: 200px; border: 1px solid #000;'>
<?php
error_reporting(E_ALL ^ E_NOTICE);
$page = $_SESSION['page'];
$pages = array('page1', 'page2', 'page3');
if (!empty($page)) {
if(in_array($page,$pages)) {
$page .= '.php';
include($page);
}
else {
echo 'Page not found. Return
<a href="includes.php">home</a>';
}
}
else {
include('page1.php');
}
?>
</div>