Page 1 of 1

Restrict extensions for upload (blob)

Posted: Tue Aug 21, 2007 9:18 pm
by kkonline
Hi, I am using a fileupload script which stores data in medium blob.

I want to have a check and allow only txt, doc and zip files to be uploaded, for other file extensions it should show an error.

Where and how do to this task?

The code is as

Code: Select all

<?
if(isset($_POST['upload']))
{

// Strip slashes from all GPC data
if (get_magic_quotes_gpc()) {
    function strip_gpc_slashes(&$array) {
        if (!is_array($array)) {
            return;
        } foreach ($array as $key => $val) {
            is_array($array[$key]) ? strip_gpc_slashes($array[$key]) : ($array[$key] = stripslashes($val));
        }
    }
       
    $gpc = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST, &$_FILES);
    strip_gpc_slashes($gpc);
}
		$fileName = $_FILES['userfile']['name'];
		$tmpName  = $_FILES['userfile']['tmp_name'];
		$fileSize = $_FILES['userfile']['size'];
		$fileType = $_FILES['userfile']['type'];
		
		$fp = fopen($tmpName, 'r');
		$content = fread($fp, $fileSize);
		$content = mysql_real_escape_string($content);
		fclose($fp);
		
		$fileName = mysql_real_escape_string($fileName);
		$contributed_by = mysql_real_escape_string($_POST['contributed_by']);
		$title = mysql_real_escape_string($_POST['title']);
			
		include 'library/config.php';
		include 'library/opendb.php';
		
		$query = "INSERT INTO upload (contributed_by, title, filename, size, type, content ) ".
		         "VALUES ('$contributed_by', '$title', '$fileName', '$fileSize', '$fileType', '$content')";

		mysql_query($query) or die('Error, query failed');					
		include 'library/closedb.php';
		
		echo "<br>File $fileName uploaded<br>";
}		
?>
Also any suggestions about the security concerns or an efficient code are welcome

Posted: Wed Aug 22, 2007 5:07 am
by volka
You can use FileInfo to determine the actual content type.
The result would also replace $fileType since $_FILES['userfile']['type']; is a value the client sent with the http request, it's not trustworthy. I can send a vbscript and tag it as image/gif.

I'd use finfo_buffer after reading the file's content to $content.

Instead of
$fp = fopen($tmpName, 'r');
$content = fread($fp, $fileSize);
...
fclose($fp);
You might want to just use file_get_contents.