In your original script you had defined the function inside your loop. Don't do that.
You can use:
Code:
$ext = substr($file_name, strrpos($file_name, '.') + 1); // File extension ex 'jpeg'
to get the extension of a file.
Check out the code I wrote below for handling multiple photo uploads. If you can use any of it, great!
You should also learn to use a MySQL database for keeping track of stuff like this. If I can do it, you can too!
Good luck,
Jason
Code:
$errors = array();
foreach ($_FILES['photos']['error'] as $key => $error) {
if ( $_FILES['photos']['size'][$key] > 0 ){
if ($error == UPLOAD_ERR_OK ) {
$tmp_name = $_FILES["photos"]["tmp_name"][$key];
$file_name = basename($_FILES['photos']['name'][$key]); // File name ex: 'theme.jpg'
$ext = substr($file_name, strrpos($file_name, '.') + 1); // File extension ex 'jpeg'
$upload_dir = UPLOAD_DIR;
$allowed_ext = array("jpg", "jpeg"); // Allowed file extensions
$allowed_type = array("image/jpeg", "image/pjpeg"); // Allowed mime types
$photo_info = getimagesize($tmp_name);
if ( !in_array($ext, $allowed_ext) ) { // Check for allowed file extension
$errors[] = '<p class="error">Uploaded files must have a .jpg or .jpeg extension. Your file: ' . "$file_name" . ' has an extenstion of ' . ".$ext" . '</p>';
}
if ( in_array($photo_info['mime'], $allowed_type) ) {
$type = "photo";
} else {
$errors[] = '<p class="error">Uploaded files must be of the correct type ("image/jpeg" or "image/pjpeg"). Your file: ' . "$file_name" . ' is being reported as ' . $photo_info['mime'] . '</p>';
}
if ($_FILES['photos']['size'][$key] <= 2000000 ) { // Check for maximum allowed size 2 MB 1000 K 2000000 bytes
$file_size = ($_FILES['photos']['size'][$key]/1000);
} else { // File size is NOT ok
$errors[] = "<p class=\"error\">Uploaded files must be less than 2000 KB ( 2 MB ). $file_name is $file_size KB.</p>";
}
if ( empty($errors) ) {
$new_file_name = substr(md5($_SESSION['U_ID'] . rand(0,999)),0,6) . "$type" . ".$ext";
// Move file
if ( move_uploaded_file("$tmp_name", UPLOAD_DIR . "$new_file_name") ) { // Move file to final storage directory
$q = "INSERT INTO `files` (
`file_id` ,
`file_name` ,
`file_location` ,
`file_type` ,
`file_date`
)
VALUES (
NULL , '$new_file_name', '$upload_dir', '$type', NOW( )
) ";
mysql_query($q) or die(mysql_error());
$success_msg = "<p></p>" ;
} else {
$errors[] = "<p>There was a problem saving this file: $file_name .</p>";
}
}
} else {
$errors[] = "<p>There was a problem saving one of your photos. Each photo must be less than 2000 KB.</p>";
}
}
}
Bookmarks