Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Filenames

It’s fairly easy to construct a filename that refers to something other than what you intended. For example, say you have a $username variable that contains the name the user wants to be called, which the user has specified through a form field. Now let’s say you want to store a welcome message for each user in the directory /usr/local/lib/greetings, so that you can output the message any time the user logs into your application. The code to print the current user’s greeting is:

<?php include("/usr/local/lib/greetings/$username") ?>

This seems harmless enough, but what if the user chose the username "../../../../etc/passwd"? The code to include the greeting now includes /etc/passwd instead. Relative paths are a common trick used by hackers against unsuspecting scripts.

Another trap for the unwary programmer lies in the way that, by default, PHP can open remote files with the same functions that open local files. The fopen( ) function and anything that uses it (e.g., include( ) and require( )) can be passed an HTTP or FTP URL as a filename, and the document identified by the URL will be opened. Here’s some exploitable code:

<?php
  chdir("/usr/local/lib/greetings");
  $fp = fopen($username, "r");
?>

If $username is set to "http://www.example.com/myfile", a remote file is opened, not a local one.

The situation is even more dire if you let the user tell you which file to include( ):

<?php
  $file = $_REQUEST['theme'];
  include($file);
?>

If the user passes a theme parameter of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata