Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Yesterday I asked a question about how to include files passed in via the URL, and someone give me this:

if (isset($_GET['file'])){
  include($_GET['file'].'.php');
}

But one of the answers told me to do something with this to avoid possible attacks from hackers or something like that. The problem is that I don't understand how to do it myself.

He said I should do something like this:

$pages_array=('home','services','contact').

And then check the GET var:

if(!in_array($_GET['page'], $pages_array) { die(); }

What does this do, and how do I integrate it into my original code above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your original code is looking for a file parameter in the URL, and then including whatever file was passed in. So if somebody goes to your PHP page and adds ?file=something.txt to the URL, you'll include the contents of something.txt in your output.

The problem with this is that anybody can manually modify the URL to try to include whatever file they want - letting them see files on your system that should be private.

The solution is to have a list of allowed filenames, like this:

$pages = array('home', 'services', 'contact');

And then before you include the file, check that it's one of the allowed filenames first.

$pages = array('home', 'services', 'contact');
if (isset($_GET['file'])){
    if (!in_array($_GET['file'], $pages_array)) {
        exit('Not permitted to view this page');
    }
    include($_GET['file'].'.php');
}

We're using a PHP array to define the list of allowed pages, checking if our page is in the list with the in_array() function, and then stopping all script execution if it's not in the list with the exit() function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...