How to Handle Files in Joomla

The base for file handling is the JFile class

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" />

1. Get the file details

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

$input = JFactory::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

To clean up filename to get rid of strange characters and spaces:

$filename = JFile::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 = JFile::getExt($filename);

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

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


4. Get the file name without extension

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

$name = JFile::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 (JFile::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.

JFile::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. 



Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive