How to use the filesystem package

From Joomla! Documentation

Using the JFile:: class[edit]

There are 4 classes in the filesystem library.

  • JFile:: (file.php)
  • JFolder:: (folder.php)
  • JPath:: (path.php)
  • JArchive:: (archive.php)

This tutorial focuses on the JFile:: and JFolder:: classes.

The base for file handling is the JFile class, found in the /libraries/src/Filesystem/File.php file. Below you can see the most common options from this library file. At the end of this post you can find a very simple script for file upload.

Get the File Extension[edit]

Syntax:

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

Pretty clear, just feed the function with a filename and it will return the extension of the file you selected.

Strip the File Extension[edit]

Syntax:

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

This will return the filename without the extension.

Clean the Filename[edit]

Use: It cleans out all odd characters from a filename and returns a safe filename.

Syntax:

$safefilename = File::makeSafe($filename);


REQUIRES:

use Joomla\CMS\Filesystem\File;

Normally at the head of the file.

Copy a File[edit]

Syntax:

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

It is basically a wrapper for the PHP copy() function, but also checks if the file you want to copy exists and the destination really is available. The great thing is that this function also makes use of the FTP-layer in J15 if necessary.

Delete a File[edit]

Syntax:

JFile::delete($path.$file);

It tries to delete the file, making sure it actually exists, but also checks permissions. If permissions are not set up properly, it tries to change them and delete the file. It also uses the FTP-layer when necessary.

Upload a File[edit]

Syntax:

JFile::upload($src, $dest);

It is basically the wrapper for the PHP move_uploaded_file() function, but also checks availability and permissions on both source and destination path.

Example[edit]

So how does that look in a script? Here's a small code snippet of an upload script. Some of the functions are used. The script is fired from an upload form. That form has a file element, called file_upload (see below).

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

Note: If you didn't add the part: enctype="multipart/form-data" then you are unable to upload a file.

The upload code looks like this:

<?php
/*
* File upload example
*/
// Retrieve file details from uploaded file, sent from upload form
$file = JFactory::getApplication()->input->files->get('file_upload');

// Import filesystem libraries. Perhaps not necessary, but does not hurt.
jimport('joomla.filesystem.file');

// Clean up filename to get rid of strange characters like spaces etc.
$filename = JFile::makeSafe($file['name']);

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

// First verify that the file has the right extension. We need jpg only.
if (strtolower(JFile::getExt($filename)) == 'jpg') 
{
   // TODO: Add security checks.

   if (JFile::upload($src, $dest))
   {
      // Redirect to a page of your choice.
   } 
   else
   {
      // Redirect and throw an error message.
   }
}
else
{
   // Redirect and notify user file does not have right extension.
}
?>

Using the JFolder:: Class[edit]

The base for folder handling is the JFolder class, found in the /libraries/src/Filesystem/Folder.php file. Below I will discuss the most common options from this library file. At the end there is a simple example script.

Copy Folder[edit]

Syntax:

JFolder::copy($src, $dest, $path, $force);

This will copy a complete folder and all of its contents to another location on the server. It does permission and availability checking on both source and destination. By using $path you can enter a base path to prefix to the filename and by setting the $force parameter to true, you can force the overwriting of already existing files. If set in the configuration, the FTP-layer will be used.

Create Folder[edit]

Syntax:

JFolder::create($path, $mode);

This is basically a wrapper for the PHP mkdir() function, but with error permissions and availability checking. This one also uses the FTP-layer when set in the configuration. $mode will set the default permission, once copied and defaults to 0755.

If any parent directory does not exist, it is created. If the directory to be created ($path) already exists, this function just returns a Boolean true.

Move folder[edit]

Syntax:

JFolder::move($src, $dest);

Basically a wrapper for the PHP rename() function, but with permissions and availability checking. This one also uses the FTP-layer when set in the configuration.

Check If a Folder Exists[edit]

Syntax:

JFolder::exists($path);

Wrapper for the PHP is_dir() function. Returns true if the folder exists.

Read Files from a Folder[edit]

Syntax:

JFolder::files($path, $filter = '.', $recurse, $fullpath , $exclude);

A function to read files from a folder. When setting $recurse to true, subfolders will also be searched. $fullpath set to true returns the full path in the array. With $exclude, you can offer an array of extensions, not to include in the search for files. It returns an array with all filenames.

Read Folders from Filesystem[edit]

Syntax:

JFolder::folders($path, $filter = '.', $recurse, $fullpath , $exclude);

The same as JFolder::files(), except this only returns an array with folder names.

Make a Tree-Like List from a Folder Structure[edit]

Syntax:

JFolder::listFolderTree($path, $filter, $maxLevel = 3, $level = 0, $parent = 0);

It will read a folder, specified in $path and will return all folders in an array, suitable for tree display. You can specify the number of levels. The folder array looks like this:

Array
(
    [0] => Array
        (
            [id] => 1
            [parent] => 0
            [name] => administrator
            [fullname] => g:/joomla_1012/administrator
            [relname] => g:/joomla_1012/administrator
        )

    [1] => Array
        (
            [id] => 2
            [parent] => 1
            [name] => backups
            [fullname] => g:/joomla_1012/administrator/backups
            [relname] => g:/joomla_1012/administrator/backups
        )

    [2] => Array
        (
            [id] => 3
            [parent] => 1
            [name] => components
            [fullname] => g:/joomla_1012/administrator/components
            [relname] => g:/joomla_1012/administrator/components
        )
)

Clean a Path String[edit]

Syntax:

JFolder::makeSafe($path);

Similar to the JFile::makeSafe() function. It cleans all odd characters out of the string and returns a clean path.

Example[edit]

How does this look in actual code? We are going to read the contents of a folder called images that holds a number of files. We want to create a subfolder, called jpg and filter all jpg files out and move them to the jpg subfolder. After that, we will move the complete subfolder to another place on the server.

<?php
// First we set up parameters.
$searchpath = JPATH_COMPONENT . '/images';

// Import the folder system library.
jimport('joomla.filesystem.folder');

// Then we create the subfolder called jpg.
if (!JFolder::create($searchpath . "/jpg"))
{
   // Throw error message and stop script.
}

// Now we read all jpg files and put them in an array.
$jpgFiles = JFolder::files($searchpath, '.jpg');

// Now we need some stuff from the ''JFile:: class'' to move all the files into the new folder.
foreach ($jpgFiles as $file)
{
   JFile::move($searchpath . '/' . $file, $searchpath . '/' . 'jpg' . $file);
}

// Last we move the complete subdir to the root of the component.
if (JFolder::move($searchpath . '/'. 'jpg', JPATH_COMPONENT))
{
   // Redirect with perhaps a happy message.
}
else
{
   // Throw an error.
}
?>