Reputation: 343
I use a php script to include another php file. When someone goes to the index.php with the wrong string, I want it to show on the screen an error message.
How do I make it show a custom error message like "You have used the wrong link. Please try again."?
Here is what I am doing now...
Someone comes to the URL like this...
http://example.com/?p=14
That would take them to the index.php
file and it would pick up p
. In the index.php
script it then uses include ('p'.$p.'/index.php');
which finds the directory p14
and includes the index.php
file in that directory.
I am finding people, for what ever reason, are changing the p=
and making it something that is not a directory. I want to fight against that and just show an error if they put anything else in there. I have too many directories and will be adding more so I can't just us a simple if ($p != '14'){echo "error";}
I would have to make about 45 of those.
So what is a simple way for me to say.... "If include does not work then echo "error";"?
Upvotes: 0
Views: 215
Reputation: 803
$filename = 'p'.$p.'/index.php';
Solution1:
if(!@include($filename)) throw new Exception("Failed to include ".$filename);
Solution2: Use file_exists - this checks whether a file or directory exists, so u can just check for directory as well
if (!file_exists($filename)) {
echo "The file $filename does not exist";
}
Upvotes: 2
Reputation: 381
You should never use this include solution, because it can be vulnerable to code injection.
Even using file_exists is not a good solution, because the attacker can try some files in your server that was not properly secured and gain access to them.
You should use a white list: a dictionary containing the files that the user can include referenced by an alias, like this:
$whiteList = array(
"page1" => "/dir1/file1.php",
"page2" => "/dirabc/filexyz.php"
)
if (array_key_exists($p, $whiteList)) {
include_once($whiteList[$p]);
} else {
die("wrong file");
}
In this way you do no expose the server files structure to the web and guarantee that only a file allowed by you can be included.
You must sanitize the $p
before using it:
$p = filter_input(INPUT_GET, "p", FILTER_SANITIZE_STRING);
But depending on the keys that you use in the dictionary, other filters should be used... look at the reference.
Upvotes: 1
Reputation: 304
if(!file_exists('p'.$p.'/index.php')) die('error');
require_once('p'.$p.'/index.php');
Upvotes: 1