Re: does this code look like it would check a file extensions, and disallow php files or exe files to be attached

From: Date: Thu, 14 Jun 2007 14:12:40 +0000
Subject: Re: does this code look like it would check a file extensions, and disallow php files or exe files to be attached
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-256997@lists.php.net to get a copy of this message
On 6/14/07, dave peaachepea <peaachepea@gmail.com> wrote:
<?php $filelinks=t3lib_div::_POST('file_name'); // the posting of the file name
$exttypes = "php3,php,exe";                                     // list of
extensions that shouldnt be used
$fileextension = substr($filelinks,0,strpos($filelinks,"."));     //get the
extension after the .
if ($fileextension == $exttypes['php']['php3']['exe']) {         //if the
file extension equals php, php3, or exe
    echo "mime type doesn't work";                                 //if the
extension is php, php3, exe, than echo doesn't work
    }
    if ($fileextension != $extypes['php']['php3']['exe']) {     //if the
file extension doesn't equal php, php3, or exe than
                                                                // store the
file
        $filelinks = $this->storeFile();
        }
?> I'm not a programmer, and I'm very new at php so im sure there are errors and stupid logic in my code. It would be greatly appreciated if anyone here could critique and rip apart my code. thank you, -dave
Since you're new to programming you probably haven't heard of regular expressions. They come in very handy in a case like this one. $files = array("test.htm", "test.php", "test.exe", "test.jpg", "test.jpg.exe", "test.exe.jpg"); $forbidden_extensions = array("php3","php","exe"); foreach($files as $file) { preg_match("/.*\.(\w+)$/", $file, $extension); if(in_array($extension[1], $forbidden_extensions)) { echo "File $file is not allowed <br />"; } else { echo "File $file was uploaded <br />"; } } This will produce the output: File test.htm was uploaded File test.php is not allowed File test.exe is not allowed File test.jpg was uploaded File test.jpg.exe is not allowed File test.exe.jpg was uploaded a regular expressions is enclosed in / / . matches anything and a * means 0 or more. So the regular expressions starts matching 0 or more of anything. Then I escape the . ( the \. part) to match a . and then I put parenthesis to create a capture and \w means alphanumeric characters and + means 1 or more. The $ means the end. So that regular expression looks for a . followed by alphanumeric characters and returns those alphanumeric characters. If you didn't understand everything in there that's fine, just read this: http://www.regular-expressions.info/tutorial.html . It's an excellent regular expression tutorial and after reading it you'll see what was going on.

« previous php.general (#256997) next »