Php: Create Variable Based On Hashtag
Solution 1:
Only the page4
works, because it is expecting the scripts to be named like page_number.html
. Your home, about, services
do not match that pattern. To make them work as well, you would need to change the file_get_contents()
call to allow page/anything.html
.
The first thing to modify is the function which posts:
functionloadPage(url)
{
// Instead of stripping off #page, only // strip off the # to use the rest of the URL
url=url.replace('#','');
$('#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');
}
}
});
}
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 ../../../../somefile
to 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.
if(empty($_POST['page'])) die("0");
// Remove the typecast so you can use the whole string//$page = (int)$_POST['page'];// Just use the post val. This is safe because we'll validate it with preg_match() before use...$page = $_POST['page'];
// And validate it as alphanumeric before reading the filesystemif (preg_match('/^[a-z0-9]+$/i', $_POST['page']) && file_exists('pages/'.$page.'.html')) {
// Remove the page_ to use the whole thingecho file_get_contents('pages/'.$page.'.html');
}
elseecho'There is no such page!';
Solution 2:
You'd need to alter more than just this to get it working.
Change the JS so that it doesn't remove anything from the URL except the pound sign:
url=url.replace('#page','');
Needs to be:
url=url.replace('#','');
Change the PHP to handle strings:
if(!$_POST['page']) die("0"); // Only allow alphanumeric characters and an underscore in page names$page = preg_replace( "/[^\w]/", '', $_POST['page']); if(file_exists('pages/'.$page.'.html')) echo file_get_contents('pages/'.$page.'.html'); elseecho'There is no such page!';
Now create the pages in the
pages/
directory.<li><a href="#home">Home</a></li>
would behome.html
<li><a href="#about">About</a></li>
would beabout.html
<li><a href="#services">Services</a></li>
would beservices.html
<li><a href="#page4">Page 4</a></li>
would bepage4.html
Solution 3:
Change the PHP to this:
$page = $_POST['page'];
if(file_exists('pages/'.$page.'.html'))
echo file_get_contents('pages/'.$page.'.html');
Now you are using the whole hash tag so #about will lead to: pages/about.html
Change this in thee javascript function loadPage
url=url.replace('#page','');
becomes
url=url.replace('#','');
Post a Comment for "Php: Create Variable Based On Hashtag"