How to Handle Files in Joomla

The base for file handling is the File class. It is part of Filesystem library which includes File, Folder and Path.

First, you need to add the attribute enctype="multipart/form-data" to the form. Otherwise, you are unable to upload a file.

<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" />

To use static methods of the File class, use the following namespace:

use Joomla\CMS\Filesystem\File;

1. Get the file details

To retrieve file details from the uploaded file, sent from upload form:

$input = Factory::getApplication()->input;
$file = $input->files->get('file_upload');

The variable $file is an array. After getting the file, you can access its details:

  • file['name'] : joomla_icon.png
  • file['type'] : image/png
  • file['tmp_name'] : /tmp/phpXoIpSD
  • file['error'] : 0
  • file['size'] : 3440 (in bytes)

2. Clean the file name

Clean up the filename to get rid of strange characters and spaces:

$filename = File::makeSafe($file['name']);

3. Get the file extension

Just feed the function with a filename and it will return the extension of the file you selected.

$ext = File::getExt($filename);

To check if the file has the right extension, for example, jpg only

if (strtolower(File::getExt($filename)) == 'jpg') 


4. Get the file name without extension

To strip the file extension and return the filename without the extension:

$name = File::stripExt($filename);

5. Upload File

The function also checks availability and permissions on both, source and destination path.

// Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . "/uploads/" . $filename;

if (File::upload($src, $dest))
$this->setMessage('File is uploaded');
$this->setMessage('File is not uploaded');

6. Copy File

This function also checks if the file you want to copy exists and the destination really is available.

File::copy($src, $dest);

7. Delete File

The function tries to delete the file, making sure it is actually existing. It also checks permissions. If permissions are not set up properly, it tries to change them and delete the file.