PHP

Using Relative Paths for File Access

dirname(__FILE__);
basename(__FILE__);

Usually, files are opened (or searched) relative to the path of the document. If you are using PHP as an ISAPI module under Windows, the location of php4ts.dll or php5ts.dll may be relevant. To be sure that you are searching to the current scripts' path, you can use a two-step approach:

  • The constant __FILE__ contains the full path of the current script

  • The function dirname() determines the directory name portion of a path

Determining Directory Name and Filename

<?php
  $directory = dirname(__FILE__);
  $filename = basename(__FILE__);
  print "This script is called $filename and resides
    in $directory.";
?>

To use a relative path, you can now call dirname(__FILE__) and then attach the relative path, taking into consideration the directory separator character, which is / on UNIX/Linux, \on Windows, and : on Mac OS X. Usually, / works fine on most systems, but you should note the requirements of the system on which you want to host your site.

The sister function to dirname() is basename(); this one determines the filename portion of a path.

The listing at the beginning of This uses both basename() and dirname() and __FILE__ to determine information about the current path: directory and filename. Figure shows the script's output.

Detecting the script's name and its directory.


Avoiding Security Traps with File Access

One very important point: If you are using files with PHP, avoid retrieving the filename from external sources, such as user input or cookies. This might allow users to inject dangerous code in your website or force you to load files you did not want to open. Some so-called security experts had a self-programmed content management system that created uniform resource locators (URLs) like this: index.php?page=subpage.html. This just loaded the page subpage.html into some kind of page template and sent this to the browser. But what if the following URL is called: index.php?page=../../../etc/passwd? With some luck (or bad luck, depending on your point of view), the contents of the file /etc/passwd are printed out in the browser. This kind of attacka so-called directory traversal attackis quite common on the Web. How-ever, you can avoid becoming a victim in several ways:

  • If possible, do not use dynamic data in filenames.

  • If you have to use dynamic data in filenames, use basename() to determine the actual name of the file, omitting the path information.

  • Set the php.ini directive open_basedir. This expects a list of directories where PHP may access files. PHP checks the basedir rules whenever a file is opened, and refuses to do so if it isn't in the appropriate path.

  • Set include_path to a directory you put all to-be-used files into and set the third parameter to fopen() to TRue, using the include_path.

by BrainBellupdated
Advertisement: