Upload Class
The Upload class allows you to upload files safely in LavaLust. You can define various preferences, such as allowed file types, size restrictions, automatic filename encryption, and MIME type validation.
The Process
Uploading a file involves the following general process:
An upload form is displayed, allowing the user to select a file.
When the form is submitted, the file is uploaded to the destination directory.
The file is validated based on the preferences you set (extension, MIME type, size, etc.).
On success, a confirmation is displayed. Otherwise, errors are shown.
Loading the Upload Library
Before using the upload features, load it via:
<?php
$this->call->library('upload', $_FILES["userfile"]);
Note: The second parameter passes the uploaded file data to the constructor for processing.
Class Methods
Upload Class Methods
Method |
Parameters |
Return |
Description |
|---|---|---|---|
|
|
object (method chaining) |
Sets allowed file extensions. Overrides default extensions |
|
|
object (method chaining) |
Sets allowed MIME types. Overrides default MIME types |
|
|
object (method chaining) |
Sets upload directory. Creates directory if it doesn’t exist |
|
|
object (method chaining) |
Sets maximum file size in MB |
|
|
object (method chaining) |
Sets minimum file size in MB |
|
None |
object (method chaining) |
Restricts uploads to valid image files only |
|
None |
object (method chaining) |
Automatically renames uploaded file to a random encrypted filename using SHA1 |
|
|
bool |
Performs the upload process. Returns TRUE on success, FALSE on failure |
|
None |
array |
Returns an array of error messages |
|
None |
string |
Returns the final uploaded filename |
|
None |
int |
Returns the size of the uploaded file in bytes |
|
None |
string |
Returns the file extension of the uploaded file |
Method Parameters Reference
allowed_extensions() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
array |
— |
Array of allowed file extensions (e.g., |
allowed_mimes() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
array |
— |
Array of allowed MIME types (e.g., |
set_dir() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
string |
— |
Directory path where files will be saved (e.g., |
max_size() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
int |
— |
Maximum file size in megabytes (MB) |
min_size() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
int |
— |
Minimum file size in megabytes (MB) |
do_upload() Parameters
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
bool |
FALSE |
If TRUE, overwrites existing files with the same name |
|
bool |
FALSE |
If TRUE, saves file without extension |
Default Values
The Upload class comes with the following default configurations:
Default Allowed Extensions
Extension |
Description |
|---|---|
|
GIF images |
|
JPEG images |
|
JPEG images |
|
PNG images |
Default Allowed MIME Types
MIME Type |
Description |
|---|---|
|
GIF images |
|
JPEG images |
|
JPEG images |
|
PNG images |
Creating the Upload Form
Create a view file called upload_form.php inside your app/views/ directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php if (!empty($errors)): ?>
<?php foreach($errors as $error): ?>
<div style="color: red;"><?php echo $error; ?></div>
<?php endforeach; ?>
<?php endif; ?>
<form action="<?php echo site_url('upload/do_upload'); ?>" method="post" enctype="multipart/form-data">
<input type="file" name="userfile" size="20" />
<br><br>
<input type="submit" value="Upload" />
</form>
</body>
</html>
The Success Page
Create another view file called upload_success.php in the same folder:
<html>
<head>
<title>Upload Success</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<p>Filename: <?php echo $filename; ?></p>
<p>Size: <?php echo $size; ?> bytes</p>
<p>Extension: <?php echo $extension; ?></p>
</body>
</html>
The Controller
Create a controller called UploadController.php inside your app/controllers/ directory:
<?php
class UploadController extends Controller {
public function upload_form() {
$this->call->view('upload_form');
}
public function do_upload() {
$this->call->library('upload', $_FILES["userfile"]);
$this->upload
->max_size(5)
->min_size(1)
->set_dir('uploads')
->allowed_extensions(['jpg', 'jpeg', 'png'])
->allowed_mimes(['image/jpeg', 'image/png'])
->is_image()
->encrypt_name();
if ($this->upload->do_upload()) {
$data['filename'] = $this->upload->get_filename();
$data['size'] = $this->upload->get_size();
$data['extension'] = $this->upload->get_extension();
$this->call->view('upload_success', $data);
} else {
$data['errors'] = $this->upload->get_errors();
$this->call->view('upload_form', $data);
}
}
}
The Upload Directory
You will need a destination directory for your uploaded files.
Create a directory (e.g., uploads) and the system will attempt to create it if it doesn’t exist. Ensure the directory is writable by the web server.
To manually create the directory:
mkdir uploads
chmod 755 uploads
Setting Preferences
You control what is allowed to be uploaded through various preference methods. All preference methods support method chaining for cleaner code.
Basic Example:
<?php
$this->call->library('upload', $_FILES["userfile"]);
$this->upload
->max_size(5) // 5 MB maximum
->min_size(1) // 1 MB minimum
->set_dir('uploads/images') // Save to uploads/images/
->allowed_extensions(['jpg', 'png']) // Only JPG and PNG
->allowed_mimes(['image/jpeg', 'image/png']) // Only JPEG and PNG MIME types
->is_image() // Must be valid image
->encrypt_name(); // Rename with SHA1 hash
Example with Overwrite:
<?php
$this->call->library('upload', $_FILES["userfile"]);
$this->upload
->set_dir('uploads')
->allowed_extensions(['pdf', 'doc', 'docx'])
->max_size(10);
// Overwrite existing file with the same name
if ($this->upload->do_upload(TRUE)) {
echo "File uploaded (overwritten if existed)";
}
Example without Extension:
<?php
$this->call->library('upload', $_FILES["userfile"]);
$this->upload
->set_dir('uploads')
->encrypt_name();
// Save file without extension
if ($this->upload->do_upload(FALSE, TRUE)) {
echo "File saved without extension";
}
Method Chaining
All preference methods support method chaining for more concise code:
<?php
$this->call->library('upload', $_FILES["userfile"]);
$this->upload->max_size(5)
->min_size(1)
->set_dir('uploads')
->allowed_extensions(['jpg', 'png'])
->is_image()
->encrypt_name()
->do_upload();
Error Handling
Always check if the upload was successful and display appropriate error messages:
<?php
$this->call->library('upload', $_FILES["userfile"]);
$this->upload->max_size(5)->set_dir('uploads');
if ($this->upload->do_upload()) {
// Success - proceed with success logic
$filename = $this->upload->get_filename();
} else {
// Failure - display errors
$errors = $this->upload->get_errors();
foreach ($errors as $error) {
echo $error . "<br>";
}
}
Best Practices
Always validate file extensions and MIME types to prevent malicious file uploads
Use ``encrypt_name()`` to prevent filename collisions and hide original filenames
Set appropriate size limits (
max_size()andmin_size()) to control resource usageUse ``is_image()`` when expecting image uploads for additional validation
Store uploads outside the web root when possible for sensitive files
Set proper directory permissions (755 or 750) - never use 777 in production
Sanitize filenames - the class automatically sanitizes filenames using the security helper
Use unique filenames to prevent overwriting (unless intended with
$overwrite = TRUE)Limit allowed file types based on your application’s needs
Implement additional server-side scanning for virus/malware detection on uploads
Security Considerations
Warning
Never trust user-uploaded files. Always validate thoroughly before saving or serving them.
Security features built into the Upload class:
Filename sanitization (removes dangerous characters)
Extension and MIME type validation
Image validation using
getimagesize()whenis_image()is enabledAutomatic directory creation with proper permissions (755)
File permission setting to 644 after upload
Additional security recommendations:
<?php
// Restrict to specific image types only
$this->upload->allowed_extensions(['jpg', 'jpeg', 'png'])
->allowed_mimes(['image/jpeg', 'image/png'])
->is_image();
// Use encrypted names to hide original filenames
$this->upload->encrypt_name();
// Set reasonable size limits
$this->upload->max_size(5); // 5 MB max
// Store in a non-public directory when possible
$this->upload->set_dir('/var/www/private/uploads/');
Troubleshooting
Common Issues and Solutions
Issue |
Possible Solution |
|---|---|
Upload fails with “No valid file selected” |
Ensure your form has |
“Upload directory is not writable” |
Check directory permissions. Run |
“Invalid uploaded file extension” |
Add the file extension to |
“Invalid uploaded file MIME type” |
Add the MIME type to |
“Uploaded file is not a valid image” |
Enable |
“Uploaded file size is too large/small” |
Adjust |
Files are being overwritten unexpectedly |
Set |
Filename contains special characters |
The class automatically sanitizes filenames using the security helper |
Complete Example
Here’s a complete example with form, validation, and file information display:
<?php
class GalleryController extends Controller {
public function index() {
$this->call->view('gallery_upload');
}
public function upload_image() {
$this->call->library('upload', $_FILES["gallery_image"]);
$this->upload->set_dir('uploads/gallery')
->allowed_extensions(['jpg', 'jpeg', 'png', 'gif'])
->allowed_mimes(['image/jpeg', 'image/png', 'image/gif'])
->max_size(10)
->is_image()
->encrypt_name();
if ($this->upload->do_upload()) {
// Save file info to database
$image_data = array(
'filename' => $this->upload->get_filename(),
'size' => $this->upload->get_size(),
'extension' => $this->upload->get_extension(),
'mime' => $this->upload->mime,
'uploaded_at' => date('Y-m-d H:i:s')
);
// $this->db->insert('gallery_images', $image_data);
$data['success'] = true;
$data['file'] = $image_data;
$this->call->view('upload_success', $data);
} else {
$data['errors'] = $this->upload->get_errors();
$this->call->view('gallery_upload', $data);
}
}
}
Note
Always validate the uploaded file’s extension and MIME type to ensure security.
Avoid allowing executable file types (e.g., .php, .exe, .sh) to be uploaded.
The default configuration only allows common image formats for safety.