PHP validate image file extension error - php

Can anybody find the problem in this code ? It keeps returning "Invalid file extension_"
PHP version 5.3.13
<?php
Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762);
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('POST exceeded maximum allowed size.');
// Settings
$save_path = getcwd() . '/uploads/';
// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'file';
// change this accordingly
$max_file_size_in_bytes = 2147483647;
// 2GB in bytes
$whitelist = array('.jpg', '.png', '.gif', '.jpeg');
// Allowed file extensions
$backlist = array('.php', '.php3', '.php4', '.phtml','.exe');
// Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s ';
// Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = '';
$file_extension = '';
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
HandleError('No upload found in \$_FILES for ' . $upload_name);
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) ||!#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed is_uploaded_file test.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
// Validate the file size (Warning: the largest files supported by this code is 2GB)
$file_size = #filesize($_FILES[$upload_name]['tmp_name']);
if (!$file_size || $file_size $max_file_size_in_bytes)
HandleError('File exceeds the maximum allowed size');
if ($file_size <= 0)
HandleError('File size outside allowed lower bound');
// Validate its a MIME Images (Take note that not all MIME is the same across different browser, especially when its zip file)
if(!eregi('image/', $_FILES[$upload_name]['type']))
HandleError('Please upload a valid file!');
// Validate that it is an image
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && isset($imageinfo))
HandleError('Sorry, we only accept GIF and JPEG images');
// Validate file name (for our purposes we'll just remove invalid characters)
$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', '', strtolower(basename($_FILES[$upload_name]['name'])));
if (strlen($file_name) == 0 || strlen($file_name) $MAX_FILENAME_LENGTH)
HandleError('Invalid file name');
// Validate that we won't over-write an existing file
if (file_exists($save_path . $file_name))
HandleError('File with this name already exists');
// Validate file extension
if(!in_array(end(explode('.', $_FILES['file']['name'])), $whitelist))
{HandleError('Invalid file extension_');}
if(in_array(end(explode('.', $_FILES['file']['name'])), $backlist))
{HandleError('Invalid file extension');}
// Rename the file to be saved
$file_name = md5($file_name. time());
// Verify! Upload the file
if (!#move_uploaded_file($_FILES[$upload_name]['tmp_name'], $save_path.$file_name)) {
HandleError('File could not be saved.');
}
exit(0);
/* Handles the error output. */
function HandleError($message) {
echo $message;
exit(0);
}
// Validate file extension
if(!in_array(end(explode('.', $_FILES['file']['name'])), $whitelist))
{HandleError('Invalid file extension_');}
if(in_array(end(explode('.', $_FILES['file']['name'])), $backlist))
{HandleError('Invalid file extension');}
?>

Related

is_uploaded_file function worked in linux But not in Windows

Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}

php upload pdf, doc, docx

I am try to upload files to my server the allowed extension should be pdf, doc, docx
this is my code.
$uploadCv = $_FILES['uploadCv']['name'];
$target = "includes/employeeCv/";
$target = $target . basename($_FILES['uploadCv']['name']);
if ($_FILES['uploadCv']['size'] == 0) {
$error['uploadCvErr'] = "<span class='notAllowed'>Please upload your c.v</span>";
} elseif
(
$_FILES['uploadCv']['type'] != 'application/pdf'
&& $_FILES['uploadCv']['type'] != 'application/msword'
&& $_FILES['uploadCv']['type'] != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) {
$error['uploadCvErr'] = 'Unsupported file type uploaded.';
} elseif ($_FILES['uploadCv']['size'] > 5000000) {
$error['uploadCvErr'] = 'File uploaded exceeds maximum upload size.';
}
everything is going OK with PDF and doc but on docx it says Unsupported file type uploaded.
what I am doing wrong here.
Edit
I added this to my check files
&& $_FILES['uploadCv']['type'] != 'application/zip'
still not working.
OfficeOpenXML .docx files often have the application/zip mime type because they are a zipped collection of XML files, and browsers are too lazy to check beyond the zip signature when setting mime type

how to call a variable value in another php file

I have an upload script which uploads files to hosting and the redirects to success urlcode of upload script is as below. I want to get value from this to success url.
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER',$_SERVER['DOCUMENT_ROOT'].'/upload/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 0);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','http://sap.layyah.info/result.php');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array();
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', false);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');
####################################################################
END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('file-upload.html');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['name']);
// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = #strtolower(#strrchr($filename,"."));
if (#strpos($file_ext,'.') === false) { // no dot? strange
$errors[] = "Suspicious file name or could not determine file extension.";
break;
}
$file_ext = #substr($file_ext, 1); // remove dot
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;
// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
$errors[] = "File is too big (3).";
break;
}
if (!#move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
$errors[] = "Could not upload file (6).";
break;
}
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
I want to show $dest_filename on SUCCESS_URL I have tried include and echo but it is not working
In Success URL I am Using:
<?php
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
echo 'Click here for uploaded file!;
Is this what you're after??
// redirect to upload success url
header('Location: '.SUCCESS_URL."?uploaded_file_url=".DESTINATION_FOLDER."/".$dest_filename);
die();
In your successful url script put this at the top of your page:
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
If you want a hyperlink to the url of that file (for download etc), then just wrap a tags around it like so:
echo 'Click here for uploaded file!;
Try to use POST and GET to pass the string on the URL.

Encrypt name of uploaded file

I have an upload script that I found online and modified a little. I need a way to make sure that every file that is uploaded has a unique name; something short at first and as the number of files increase, the length of the name can increase too. My script I've used is...
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','../uploads/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 10240);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','my info');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array('jpg', 'jpeg', 'png', 'gif');
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', true);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');
// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG', true);
// MySql data (in case you want to save uploads log)
define('DB_HOST','my info'); // host, usually localhost
define('DB_DATABASE','my info'); // database name
define('DB_USERNAME','my info'); // username
define('DB_PASSWORD','my info'); // password
/*CREATE TABLE uploads_log (
log_id int(11) unsigned NOT NULL auto_increment,
log_filename varchar(128) default '',
log_size int(10) default 0,
log_ip varchar(24) default '',
log_date timestamp,
PRIMARY KEY (log_id),
KEY (log_filename)
);*/
####################################################################
### END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('index.php');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['name']);
// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = #strtolower(#strrchr($filename,"."));
if (#strpos($file_ext,'.') === false) { // no dot? strange
$errors[] = "Suspicious file name or could not determine file extension.";
break;
}
$file_ext = #substr($file_ext, 1); // remove dot
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;
// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
$errors[] = "File is too big (3).";
break;
}
if (!#move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
$errors[] = "Could not upload file (6).";
break;
}
if (DO_LOG) {
// Establish DB connection
$link = #mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
if (!$link) {
$errors[] = "Could not connect to mysql.";
break;
}
$res = #mysql_select_db(DB_DATABASE, $link);
if (!$res) {
$errors[] = "Could not select database.";
break;
}
/*$m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$m_size = $filesize;
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "insert into _uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}*/
#mysql_free_result($res);
#mysql_close($link);
} // if (DO_LOG)
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
Plus, what other security procedures should I use? If you know any, could you please implement them into my code and re-post them? Thank you!!!
The code you've posted already includes the lines:
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
This is a perfectly good way to generate a random unique file name in PHP. The string returned by md5() will be 32 characters long; you could safely truncate it a bit, but if you go much below 16 characters or so, you start risking collisions.
Of course, if you want to make sure there are no collisions, you could always just check whether the file exist and retry if it does. This would even allow you to use shorter filenames:
if (RENAME_FILE) {
do {
$dest_filename = substr(md5(uniqid(rand(), true)), 0, 8) . ".$file_ext";
} while (file_exists(DESTINATION_FOLDER . $dest_filename . APPEND_STRING));
}
This should give you a unique 8-character (+ extension) filename. Of course, this will start slowing down after about 231 &approx; 2 billion uploaded files, and will fail completely at 232 &approx; 4 billion.

Unable to upload images [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I was trying to upload images using the below code but it shows:
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\upload3.php on line 57
Here is what I have on line 57:
if ($file_size &lt;= 0)
HandleError('File size outside allowed lower bound'); // Validate its a MIME Images (Take note that not all MIME is the same across different browser, especially when its zip file)
When I remove the above line from the below code, I get No Session was found. on the screen and nothing else comes. Does anyone have any Idea?
<?php
#check for session
if (isset($_POST['PHPSESSID']))
session_id($_POST['PHPSESSID']);
else if (isset($_GET['PHPSESSID']))
session_id($_GET['PHPSESSID']);
else
{
HandleError('No Session was found.');
}
session_start();
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('POST exceeded maximum allowed size.');
// Settings
$save_path = getcwd() . '/pictures/'; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'file'; // change this accordingly
$max_file_size_in_bytes = 2097152; // 2MB in bytes
$whitelist = array('jpg', 'png', 'gif', 'jpeg'); // Allowed file extensions
$backlist = array('php', 'php3', 'php4', 'phtml','exe'); // Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s '; // Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = '';
$file_extension = '';
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
HandleError('No upload found in \$_FILES for ' . $upload_name);
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed is_uploaded_file test.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
// Validate the file size (Warning: the largest files supported by this code is 2MB)
$file_size = #filesize($_FILES[$upload_name]['tmp_name']);
if (!$file_size || $file_size > $max_file_size_in_bytes)
HandleError('File exceeds the maximum allowed size');
if ($file_size &lt;= 0)
HandleError('File size outside allowed lower bound'); // Validate its a MIME Images (Take note that not all MIME is the same across different browser, especially when its zip file)
if(!eregi('image/', $_FILES[$upload_name]['type']))
HandleError('Please upload a valid file!'); // Validate that it is an image
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && isset($imageinfo))
HandleError('Sorry, we only accept GIF and JPEG images');
// Validate file name (for our purposes we'll just remove invalid characters)
$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', '', strtolower(basename($_FILES[$upload_name]['name'])));
if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH)
HandleError('Invalid file name');
// Validate that we won't over-write an existing file
if (file_exists($save_path . $file_name))
HandleError('File with this name already exists');
// Validate file extension
if(!in_array(end(explode('.', $file_name)), $whitelist))
HandleError('Invalid file extension');
if(in_array(end(explode('.', $file_name)), $backlist))
HandleError('Invalid file extension');
// Rename the file to be saved
$file_name = md5($file_name. time());
// Verify! Upload the file
if (!#move_uploaded_file($_FILES[$upload_name]['tmp_name'], $save_path.$file_name))
HandleError('File could not be saved.');
exit(0);
/* Handles the error output. */
function HandleError($message) {
echo $message;
exit(0);
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
it should be <= not &lt;=

Categories