PHP HelpPHP Help

Online Community that helps beginners learn PHP,
and webmasters solve PHP coding problems

since 1999





Including Files Based on Input

Security Conscious Includes

If you're including files based on user input you must think carefully about the security implications of this. When I say user input, I mean any value coming from outside your PHP script that is used in the formation of a file path. This could be as simple as a user clicking a link containing URL-parameter whose value is a predefined path to a file you wish to include.

Let's first examine some code that accepts the name of a file and includes the contents of that file in a PHP page. The file named in the URL-parameters "body" is specified as an include.

<html>
<head>
<title>Blah</title>
<table border=1>
<tr>
<td width=100>
<a href=index.php?body=news.html>Test</a>

<td><?php include("$body"); ?>
</table>
 

Be aware this is a security risk. Suppose a mischievous user enters a link into their browser with something like this:

index.php?page=../../../etc/passwd
 

Allowing directory navigation symbols into input exposes your host system's password file and allow anyone on the web to read it. Moreover, it can expose any document on your web site. In this article, we will look at various solutions for allowing material to be included while at the same time closing this loophole.

You might think that you could just hardcode a directory or folder name into the path like this:

<a href=index.php?body=news.html>Test</a>
<td><?php include('folder/'.$body); ?>
 

But this does not work because directory navigation symbols ("../" and "./" can always be included in the path to get out of this directory. A malicious user can navigate anywhere, even out of the web tree.

Pages:  1   2Next:  Validating Include Paths »




Copyright © 2017 PHPHelp.com