There are several ways you can make a source code viewer but before I show one, I'll show how a source code viewer can be a security risk. When you make a source code viewer, you need to use a function that accepts a URL as an argument. Most functions that accept a URL as an argument can also accept a file path as an argument. If you enter a file path instead of a URL, the source code viewer will not just show the HTML code, it will also show the PHP code. This isn't a problem with external web pages because file paths will not work for them but it makes it so that someone can see the PHP code on all allmost all of your pages.
Using Javascript to validate the input is not a solution. Someone can easily copy the form and remove the Javascript to bypass it. Putting the source code viewer in a directory with "safe" files is not a solution because someone can use relative paths to check out any directory. Even having an index.html page hiding the files in a directory may not be a solution. Supose you have a "test bed" some where in you files and a hacker finds it. Using it, a hacker could enter a form with the code to list all the files in a directory.
I chose file_get_contents() for this example because it will read a file as one long string variable. Other functions, like file(), readfile() and fopen() will read a file as an array. Later on, if you want to modify part of the source code and the part being modified starts in one member of the array and ends in another, you job is much more complex. An example of this is removing multi-line javascript. file_get_contents() requires PHP5
<?
# prevent sourcing of your PHP files
if ( isset($_GET[url]) && !preg_match("@^http://@i", "$_GET[url]", $x) )
{
echo "URL's start with http://";
exit;
}
?>
<?
if ( isset($_GET[url]) )
{
/*
read surce code into a string
suppress PHP error messages
die if can't read file
*/
@$string = file_get_contents($_GET[url]) or die("Cannot read $_GET[url]");
?>
<?
$string = file_get_contents($_GET[url]) or die("Cannot read $_GET[url]");
?>
str_replace() to add line breaks to make it more readable.
htmlspecialchars() to escape all of the angle brackets so you can show the source code within a textarea.
|
|
|