Code: Select all
if ($sizeOK && $typeOK) {
switch($_FILES['image']['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['image']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// getNextFilename include to go here?
// get the date and time
ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.$file);
}
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['image']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png.";
}
Code: Select all
function getNextFilename($dir, $prefix, $type) {
// run some security checks on the arguments supplied
if (!is_dir($dir)) return false;
if (!preg_match('/^[-._a-z0-9]+$/i', $prefix)) return false;
$permittedTypes = array('txt', 'doc', 'pdf', 'jpg', 'jpeg', 'gif', 'png');
if (!in_array(strtolower($type), $permittedTypes)) return false;
// if the checks are OK, get an array of the directory contents
$existing = scandir($dir);
// create a search pattern for filenames that match the prefix and type
$pattern = '/^'.$prefix.'(\d+)\.'.$type.'$/i';
$nums = array();
// loop through the directory
// get the numbers from all files that match the pattern
foreach ($existing as $file) {
if (preg_match($pattern, $file, $m)) {
$nums[] = intval($m[1]);
}
}
// find the highest number and increase it by 1
// if no file yet created, assign it number 1
$next = $nums ? max($nums)+1 : 1;
// calculate how many zeros to prefix the number with
if ($next < 10) {
$zeros = '00';
}
elseif ($next < 100) {
$zeros = '0';
}
else {
$zeros = '' ;
}
// return the next filename in the series
return "{$prefix}{$zeros}{$next}.{$type}";
}