PHP and Website Security

[PHP-REGEX] Simple Anti-RFI/LFI Snippet

It’s been a while since my last post here in Project-X blog, now it’s time to contribute. If your application is using the local file system there are chances from time to time that your application may be vulnerable to “Remote File Inclusion” & “Local File Inclusion”. Most PHP developers say check the file first if it exist by using the file_exists function. I say it’s not enough, what you need to add a simple REGEX(Regular Expression) to check whether the given file is actually a file or a directory since file_exists is very vulnerable to RFI/LFI attacks.

Using a dual if argument with the REGEX is the complete solution 😉


if (!file_exists($filename) && !preg_match('/^(?:[a-z0-9_-]|.(?!.))+$/', $filename)) {
// do something here
}

Very simple isn’t it? I can guarantee 0% intrusions with the snippet above.

Till Then,
~n.

Leave a Reply