First try to debug your uploaded file. Secondly don't rely on the name of the file since it can be spoofed easily.
tmp_name gives you the files temporary location, which will be a random string.
Your best option is to call getimagesize
on tmp_name, for images, and finfo_open
or new finfo
for other file types to compare its mime type, you could also explode
the name and use end
which will give you an extension as well. maybe define an array of accepted extensions and use in_array
to check if extension is valid.
Will provide example code after I get to a PC.
LE: as promised a more complex check with comments and security concepts
<?php
// you can make sure you have every variable set
// then procced further
if(
isset(
$_FILES['dat'], $_FILES['dat']['tmp_name'],
$_FILES['dat']['name'], $_FILES['dat']['size'],
$_FILES['dat']['error']
)
){
$accepted = array(
'image/jpeg' => 'jpg',
'text/plain' => 'txt',
'application/zip' => 'zip',
);
$file = $_FILES['dat'];
$maxSize = 512 * 1024; // 512 KB
// check if any upload error occured
if( UPLOAD_ERR_OK !== $file['error'] ){
// http://php.net/manual/en/features.file-upload.errors.php
echo 'Upload error: ', $file['error'], '<br/>';
// check if file size is bigger than $maxSize
} elseif( $file['size'] > $maxSize ){
// if filesize is bigger than upload_max_filesize directive in php.ini
// script may timeout without any error
// post_max_size and upload_max_filesize need to be high enough
echo 'Error: File size is to big!<br/>';
// can proceed further
} else {
// you will need to have the fileinfo enabled in php ini to use these
$finfo = finfo_open( FILEINFO_MIME );
$mime = finfo_file( $finfo, $file['tmp_name'] );
// finfo may give you charset info as well
// text/plain; charset=utf-8 or image/jpeg; charset=binary
$mime = array_shift( explode( ';', $mime ) );
// change uploaded file name do to security reasons
// google "php null char upload"
// nice read http://resources.infosecinstitute.com/null-byte-injection-php/
$filename = md5( time() . $file['name'] ) . '.';
// if mime is accepted
if( ! array_key_exists( $mime, $accepted ) /* or use isset: ! isset( $accepted[ $mime ] ) */ ){
echo 'Error: Unsupported file type!<br/>';
// you could check if file is image and check min-max width & height
// for now move the uploaded file
} elseif( ! @move_uploaded_file( $file['tmp_name'], 'files/' . $filename . $accepted[ $mime ] ) ){
echo 'Unable to save uploaded image to <strong>',
htmlspecialchars( 'files/' . $filename . $accepted[ $mime ] ),
'</strong>';
} else {
echo '<a href="files/', htmlspecialchars( $filename . $accepted[ $mime ] ), '" target="_blank">',
htmlspecialchars( $filename . $accepted[ $mime ] ),
'</a>';
}
}
}