I managed to get a file upload script working. I've made sure that files that have the same name don't overwrite each other and I'm capturing some other basic information. Now I want to add a few things:
- I want to limit the acceptable file extensions to image formats
- I want to restrict the file size. I think there are a few ways to do this. I've already specified max upload size in the form and also changed the setting in php.ini. Is there a better way?
- I want to make sure people can't access the file directory if they are on my site and type in the filepath. Is this just a folder security issue?
- Are there any other important checks I'm missing?
I'm running windows XP, apache 2.2, php 5, and mysql. Here is the code:
<?
// you can change this to any directory you want
// as long as php can write to it
$uploadDir = 'C:/Apache2.2/htdocs/Devils/docs/';
if(isset($POST['upload']))
{
$fileName = $FILES['userfile']['name'];
$tmpName = $FILES['userfile']['tmp_name'];
$fileSize = $FILES['userfile']['size'];
$fileType = $FILES['userfile']['type'];
$fileTitle = $POST['title'];
$fileDescription = $_POST['description'];
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $uploadDir . $randName . '.' . $ext;
// move the files to the specified directory
// if the upload directory is not writable or
// something else went wrong $result will be false
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO images (name, size, type, path, title, description) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$filePath', '$fileTitle', '$fileDescription')";
mysql_query($query) or die('Error, query failed : ' . mysql_error());
echo "<br>File uploaded<br>";
}
?>