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 <= 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 <= 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 <=
Related
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.
I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>
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');}
?>
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 ≈ 2 billion uploaded files, and will fail completely at 232 ≈ 4 billion.
I'm working on a PHP upload script which allows .mp3 file uploads amongst others. I've created an array which specifies permitted filetypes, including mp3s, and set a maximum upload limit of 500MB:
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 5120000);
// create an array of permitted MIME types
$permitted = array('application/msword', 'application/pdf', 'text/plain', 'text/rtf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/tiff', 'application/zip', 'audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'application/x-rar-compressed');
So far in testing all specified filetypes have been successfully uploaded but for some reason it comes up with an error for .mp3. As you can see above I've included audio/mpeg, audio/mpeg3, and audio/x-mpeg-3 but none of them seem to make a difference.
Can someone suggest what the problem could be and also indicate which audio type is the one needed to allow .mp3 uploads?
Thanks
Update: The code I'm using to run the check on the file is as follows:
// check that file is within the permitted size
if ($_FILES['file-upload']['size'][$number] > 0 || $_FILES['file-upload']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of an permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['file-upload']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['file-upload']['error'][$number]) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// strip the extension off the upload filename
$filetypes = array('/\.doc$/', '/\.pdf$/', '/\.txt$/', '/\.rtf$/', '/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/', '/\.tiff$/', '/\.mpeg$/', '/\.mpg$/', '/\.mp4$/', '/\.mov$/', '/\.wmv$/', '/\.zip$/', '/\.rar$/', '/\.mp3$/');
$name = preg_replace($filetypes, '', $file);
// get the position of the final period in the filename
$period = strrpos($file, '.');
// use substr() to get the filename extension
// it starts one character after the period
$filenameExtension = substr($file, $period+1);
// get the next filename
$newName = getNextFilename(UPLOAD_DIR, $name, $filenameExtension);
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$newName);
}
if ($success) {
$result[] = "$file uploaded successfully";
}
else {
$result[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$result[] = "Error uploading $file. Please try again.";
default:
$result[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['file-upload']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: doc, pdf, txt, rtf, gif, jpg, png, tiff, mpeg, mpg, mp3, mp4, mov, wmv, zip, rar.";
}
I'm getting the bottom else result telling me either the file size is wrong or the extension isn't allowed.
Update 2:
I've run a print_r of the _FILES array to hopefully provide a little more info. The results are:
Array
(
[file-upload] => Array
(
[name] => Array
(
[0] => Mozart.mp3
[1] =>
[2] =>
)
[type] => Array
(
[0] => audio/mpg
[1] =>
[2] =>
)
[tmp_name] => Array
(
[0] => /Applications/MAMP/tmp/php/phpgBtlBy
[1] =>
[2] =>
)
[error] => Array
(
[0] => 0
[1] => 4
[2] => 4
)
[size] => Array
(
[0] => 75050
[1] => 0
[2] => 0
)
)
)
MAX_FILE_SIZE is a value in Bytes
5120000 is not 500 MB. It's 5MB by my reckoning.
You'll also need to check that you're not exceeding the "post_max_size" and "upload_max_size" variables in your php.ini file
Secondly, an mp3 can be any of the following mimetypes
audio/mpeg
audio/x-mpeg
audio/mp3
audio/x-mp3
audio/mpeg3
audio/x-mpeg3
audio/mpg
audio/x-mpg
audio/x-mpegaudio
http://filext.com/file-extension/MP3
You should never assume the value in $_FILES[...]['type'] actually matches the type of the file. The client can send any arbitrary string, and it's not checked at all by PHP. See here.
You'll have to do the work yourself to actually determine what type of file was uploaded, unless you have a good reason not to care about security at all (which you probably don't). PHP provides the fileinfo package by default, which does the heavy lifting for you. See finfo_file().
why not use in_array rather than the foreach loop for type check?
when you upload a valid file, have you tried checking the values of the $sizeOK & $typeOK
I doubt if you still need this but am sure many will also be facing this same problem. This is what I did and it worked for me.
Php Code:
if(isset($_POST['submit'])) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if ($fileType != 'audio/mpeg' && $fileType != 'audio/mpeg3' && $fileType != 'audio/mp3' && $fileType != 'audio/x-mpeg' && $fileType != 'audio/x-mp3' && $fileType != 'audio/x-mpeg3' && $fileType != 'audio/x-mpg' && $fileType != 'audio/x-mpegaudio' && $fileType != 'audio/x-mpeg-3') {
echo('<script>alert("Error! You file is not an mp3 file. Thank You.")</script>');
} else if ($fileSize > '10485760') {
echo('<script>alert("File should not be more than 10mb")</script>');
} else if ($rep == 'Say something about your post...') {
$rep == '';
} else {
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $uploadDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$sql = "INSERT INTO media SET
path = '$filePath',
size = '$fileSize',
ftype = '$fileType',
fname = '$fileName'";
if (mysql_query($sql)) {
echo('');
} else {
echo('<p style="color: #ff0000;">Error adding audio: ' . mysql_error() . '</p><br />');
}
and your html code will be;
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" class="file_input" name="userfile" />
<input type="submit" value="" name="submit" id="submitStatus" class="submit" />
</form>
The 5MB limit is probably your problem.
Here is some code that will give you some symbolic meaning to your errors:
class UploadException extends Exception {
public function __construct($code) {
$message = $this->codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
If you're getting an error from your last else statement, it is difficult to tell what exactly triggered it. Try using something like the above.
http://www.php.net/manual/en/features.file-upload.errors.php