| ||||||
|
How to validate uploaded file types in PHP
If your website has a file upload facility, the last thing you will want is your visitors being able to upload any type of file. Especially the upload of executable files could put a lot of your other users at risk if they chose to download it. Clearly then a filetype validation process is needed. Finding the right function for the job While PHP has a function called filetype(), it might not quite live up to your expectations. Its purpose is not to return the exact type of file as the name would indicate, but rather to specify if a named location is a file or folder: <? echo filetype('path/to/file.txt'); echo "<br><br>"; echo filetype('path/'); ?> The above script would return "file" on the first line and "dir" on the second. How can fileuploads be limited to specific file types then? As per usual, by using regular expressions! Validating file types with regular expressions Here is how you would limit your website uploads to PDFs and Word Documents. First we need to specify the file types that we allow, and then validate the filename with a preg_match. Then if the test is passed we can move on to copy the file to the specified destination: <?php $allowed = "(doc|docx|pdf)"; $filename = $_FILES["file"]["name"]; $tmp = $_FILES["file"]["tmp_name"]; if(preg_match("/\.".$allowed."$/i", $filename)) { copy($tmp, "path/".$filename); } ?>
|