Forum Moderators: coopster
This is my first post on this forum. I confess that I am really new at this whole PHP stuff.
I have been using this code on my site to separate my navigation and appearance from my content...
<?php
if (empty($_GET['page'])) {
include('home.php');
} else {
include($_GET['page'] . '.php');
}
?>
It works great, but whenever somebody mistypes a url or goes to an outdated bookmark, they get this...
Warning: Failed opening 'nothing.php' for inclusion (include_path='.:/php/includes:/usr/share/php') in /home/virtual/site16/fst/var/www/html/index.php on line 50
My question is: Is there any way to have the code redirect an error like this to a preset "error page?" Example: [domain.com?page=error...]
Thanks for the help!
Erick
<?php
if (!empty($_GET['page'])){
include($_GET['page'] . '.php');
}
if (empty($_GET['page'])) {
include('home.php');
} else {
header("Location: [domain.com?page=error...] "); /* Redirect browser */
}
?>
It might be sloppy. I've only been using PHP for a couple of weeks, and it is the only language I've tried to learn. Good Luck and welcome to WW!
It deals with the problems caused by using user defined url's to get an include file. Your code as written now would allow anyone to insert a remote url into your script, then run anything they wanted on your server.
I'm not a php expert, but I believe the correct syntax for the function you are trying to make is this:
if (!isset($_GET['page'])) {
include('home.php');
}
else {
include($_GET['page'] . '.php');
}
however, if a user wants to at this point they can type in this: [badsite.com...]
then that script will be what runs. The thread above has some solid advice on how to protect your site from this kind of problem.
To solve the other part of the problem, you might use the file_exists() function to make sure that the requested file actually exists. file_exists() requires that you have the absolute full server path for your file, not the path relative to your web directory.
$_SERVER['DOCUMENT_ROOT'] will give you the first part of the path, then you concatenate the actual requested path to that.
Another benefit of this is that users won't be able to put in external url's, since that would come out like this:
/usr/www/yoursite/http://badsite/mean_script.php which doesn't exist on your server.
if (!isset($_GET['page']))
{
include('home.php');
}
else
{
$full_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['page'] . '.php';
if ( file_exists( $full_path ) )
{
include($_GET['page'] . '.php');
}
else
{
include('error_page.php');
}
}
The best advice I can give you is to always assume that there is a better way to do something than what you currently can do, then look for it as you learn.