Secure PHP Code

Secure PHP Code

<?php

readfile($filename);

?>

Turning off register_globals doesn’t make this any more secure. The script would instead look like this:

<?php

readfile($HTTP_POST_VARS[’filename’]);

?>

The only way to secure something like this is to be really good way to clear user input. In this case if you really want the user to be able to specify a filename that gets used in any of PHP’s file functions, do something like this:

<?php

$doc_root = $HTTP_SERVER_VARS[’DOCUMENT_ROOT’];

$filename = realpath($filename);

readfile($doc_root.$filename);

?>

You may also want to strip out any path and only take the filename component. An easy way to do that is to use the basename() function. Or perhaps check the extension of the file. You can get the extension using this code:

<?php

$ext = substr($str,strrpos($str,’.'));

?>

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.