Restrict extensions for upload (blob)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kkonline
Forum Contributor
Posts: 251
Joined: Thu Aug 16, 2007 12:54 am

Restrict extensions for upload (blob)

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
Post Reply