How to use the filesystem package

From Joomla! Documentation

Using the JFILE:: class[edit]

There are 4 classes in the J15 filesystem library.

  • JFile:: (file.php)
  • JFolder:: (folder.php)
  • JPath:: (path.php)
  • JArchive:: (archive.php)[/i]

For this first tutorial, I will focus on the JFile:: class.

The base for filehandling is the JFile class, found in libraries/joomla/filesystem/file.php Below I will discuss the most common options from this library file. At the end of this post, I put it together in a very simple script for file upload.

Get 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 file extension[edit]

Syntax:

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

This will return the filename without the extension.

Clean filename[edit]

Syntax:

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

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

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. 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 is actually existing, 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 does checks availability and permissions on both source and destination path.

Example[edit]

So how does that look in a script? I put up 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>

Upload code looks like this:

<?php
***********************
*                     *
* File upload example *
*                     *
***********************
//Retrieve file details from uploaded file, sent from upload form
$file = JRequest::getVar('file_upload', null, 'files', 'array');

//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 check if the file has the right extension, we need jpg only
if ( strtolower(JFile::getExt($filename) ) == 'jpg') {
   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 is not right extension
}
?>

Upload - Full Sample[edit]

Little sample where admin choose the file type or all, enter the users to access the form upload. Folder to upload files in Joomla directory or with absolute path. Only selected users access the form upload.


mod_simpleupload.xml

<?xml version="1.0" encoding="utf-8"?>

<install type="module" version="1.5.0">

<name>Simple Upload 1.3</name>

<author>Ribamar FS</author>

<creationDate>fevereiro 2010</creationDate>

<copyright>(C) 2005 Open Source Matters. All rights reserved.</copyright>

<license>http://www.gnu.org/copyleft/gpl.html GNU/GPL</license>

<authorEmail>ribafs@gmail.com</authorEmail>

<authorUrl>http://ribafs.org</authorUrl>

<version>1.3</version>

<description>Simple Upload 1.3 - Simple upload with Joomla Framework.</description>

<files>

<filename module="mod_simpleupload">mod_simpleupload.php</filename>

</files>

<params>

<param name="dir" type="text" label="Directory" description="Directory Upload" default="upload"/>

       <param name="type" type="list" default="*" label="Select a file type" description="File type">
            <option value="*">Any File </option>
            <option value="image/png">PNG</option>
            <option value="image/gif">GIF</option>
            <option value="image/jpeg">JPEG</option>
            <option value="application/zip">ZIP</option>
            <option value="application/x-gzip">TAR.GZ</option>
            <option value="text/html">HTML</option>
            <option value="text/plain">TXT</option>
            <option value="application/pdf">PDF</option>
            <option value="application/msword">DOC</option>
          </param>          

<param name="user_names" type="text" label="User Names (optional)" description="Names users (optionas)" default=""/> </params>

</install>


mod_simpleupload.php

<?php

// no direct access

defined('_JEXEC') or die('Restricted access');

//Import filesystem libraries. Perhaps not necessary, but does not hurt

jimport('joomla.filesystem.file');


$max = ini_get('upload_max_filesize');

$module_dir = $params->get( 'dir' );

$file_type = $params->get( 'type' );

$user_names = $params->get( 'user_names' );

$msg = ;

function fileUpload($max, $module_dir, $file_type, $msg){

//Retrieve file details from uploaded file, sent from upload form

$file = JRequest::getVar('file_upload', null, 'files', 'array');

// Retorna: Array ( [name] => mod_simpleupload_1.2.1.zip [type] => application/zip

// [tmp_name] => /tmp/phpo3VG9F [error] => 0 [size] => 4463 )

if(isset($file)){

//Clean up filename to get rid of strange characters like spaces etc

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

if($file['size'] > $max) $msg = JText::_('ONLY_FILES_UNDER').' '.$max;

//Set up the source and destination of the file

$src = $file['tmp_name'];

$dest = $module_dir . DS . $filename;

//First check if the file has the right extension, we need jpg only

if ($file['type'] == $file_type || $file_type == '*') {

if ( JFile::upload($src, $dest) ) {

//Redirect to a page of your choice

$msg = JText::_('FILE_SAVE_AS').' '.$dest;

} else {

//Redirect and throw an error message

$msg = JText::_('ERROR_IN_UPLOAD');

}

} else {

//Redirect and notify user file is not right extension

$msg = JText::_('FILE_TYPE_INVALID');

}

$msg = "<script>alert('". $msg ."');</script>";

}

return $msg;

}

$user =& JFactory::getUser();

$username = $user->get('username');

$acc = 0;

$session =& JFactory::getSession();

if(isset($user_names)) {

$more = strpos($user_names, ',',0);

if($more >0){

$user_names = explode(',',$user_names);

foreach($user_names as $un){

if($un == $username) {

$session->set($acc, 1);

}else{

$session->set($acc, 0);

}

}

}else{

if ($user_names == $username) $session->set($acc, 1);

}

}else{

if(isset($username)) $session->set($acc, 1);

}

if($session->get($acc) == 1){

?>

<form name="imgform" method="post" action="" enctype="multipart/form-data" onSubmit="if(file_upload.value==) {alert('Choose a file!');return false;}">

<?php echo JText::_('CHOOSE_FILE'); ?> <input type="file" name="file_upload" size="10" />

<input name="submit" type="submit" value="Upload" />

</form>

<?php

print fileUpload($max, $module_dir, $file_type, $msg);

}

// Adaptação de http://docs.joomla.org/How_to_use_the_filesystem_package

?>

Using the JFolder:: class[edit]

The base for folder handling is the JFolder class, found in libraries/joomla/filesystem/folder.php Below I will discuss the most common options from this library file. At the end of this post, I put it together in a very simple script as an exmaple

Copy folder[edit]

Syntax:

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

This will copy a complete folder and all of it’s 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 basepath 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.

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 folder exists[edit]

Syntax:

JFolder::exists($path);

Wrapper for the php is_dir() function. Pretty straightforward, returns true if folder exists.

Read files from folder[edit]

Syntax:

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

Function to read files from a folder. When setting $recurse to true, also subfolders will 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);

Exactly the same as JFolder::files(), except this does only return an array with foldernames.

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);

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

Example[edit]

Ok, and how does this look in actual code. We are going to read the contents of a folder called images. In it, al large number of files are placed. 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 . DS . "images";

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

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

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

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

This is example script only, but gives a general idea of the possibilities. I did not touch other stuff like JError to keep it clean and simple.