I’m using this tutorial to create an ajax site and am struggling with the PHP. This is the provided code:
PHP
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
I would like to use a naming structure other than page_1.html, page_2.html etc. My HTML looks like this:
HTML
<ul id="navigation">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#page4">Page 4</a></li>
</ul>
Right now the only link that’s working is ‘Page 4’. How would I rewrite the PHP so that the first three links would work?
Javascript
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Only the
page4works, because it is expecting the scripts to be named likepage_number.html. Yourhome, about, servicesdo not match that pattern. To make them work as well, you would need to change thefile_get_contents()call to allowpage/anything.html.The first thing to modify is the function which posts:
Now, this introduces a security risk in PHP. You need to validate that the value of
$_POST['page']is strictly alphanumeric so that no one can inject a filename like../../../../somefileto read your filesystem. Using the expression below will allow you to name your files with any alphabetic and numeric characters, but will reject dots and null bytes, which are the primary dangers in a file path-injection / directory traversal attack.