note 51749 deleted from function.include by aidan
| From: | aidan@php.net | Date: | Sat, 15 Apr 2006 16:36:19 +0000 |
| Subject: | note 51749 deleted from function.include by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-108167@lists.php.net to get a copy of this message | ||
Note Submitter: necrotic at gmail dot com
----
To expand on marco_ at voxpopuli-forum dot net's and redeye at cs-aktuell dot de's notes,
here's a function to securely include files with direct output or a return.
<?php
/* The DOC_ROOT constant should set on it's own just fine. If you would like to set a
sub-directory, just tack it on to the end.
For example:
define ( 'DOC_ROOT', $_SERVER["DOCUMENT_ROOT"]."/inc_dir" );
define ( 'DOC_ROOT', $_SERVER["DOCUMENT_ROOT"]."/stuff/inc_dir" );
NOTE: Leave the trailing slash off. It shouldn't make a difference mostly, but just in case ;)
*/
define ( 'DOC_ROOT', $_SERVER["DOCUMENT_ROOT"] );
/* Fill this with all forbidden files. It only requires a filename, not the directory.*/
$badFiles = array (
'database.inc.php'
);
/* Fill this with all forbidden directories. Please provide the absolute path, with DOC_ROOT
starting the path. Please see the example already in the array.*/
$badDirs = array (
DOC_ROOT.'/private',
);
/**
* Provides a secure method of including files.
*
* @param string $file the file to include
* @param bool $return wether or not to output directly or return via output buffering
* @return bool|string false on failure, true on success without $return=true, string
* with file with $return=true
* @author James "necrotic" Logsdon <necrotic at gmail dot com>
* @version 1.0
*/
function secure_include ( $file, $return = false )
{
global $badFiles, $badDirs;
if ( !is_array ( $badFiles ) OR !isset ( $badFiles ) ) $badFiles = array();
if ( !is_array ( $badDirs ) OR !isset ( $badDirs ) ) $badDirs = array();
// Get path information
$realPath = realpath ( $file );
$dirName = dirname ( $realPath );
$baseName = basename ( $realPath );
if ( !$realPath )
{
// The file wasn't found by realpath, so we have a 404.
echo '<h1>404 Not Found</h1> We could not find the file you tried to
load.';
return false;
}
else if ( in_array ( $baseName, $badFiles ) OR
in_array ( $dirName, $badDirs ) OR
!strstr ( $realPath, DOC_ROOT ) )
{
// Oh crap! It's a forbidden file!
echo '<h1>403 Forbidden</h1> You do not have permission to view this
file.';
return false;
}
else if ( !$return )
{
// We're safe, include away!
include_once ( $file );
return true;
}
else
{
ob_start();
include_once ( $file );
$page = ob_get_contents();
ob_end_clean();
return $page;
}
}
/*
* Usage
* secure_include ( 'file.txt' ); // returns true if exists, outputs error or file
* secure_include ( 'file.txt', true ); // returns the file if exists, outputs error if not
or 403 Forbidden
*/
?>