Difference between revisions of "How to use the filesystem package"

From Joomla! Documentation

 
(23 intermediate revisions by 12 users not shown)
Line 1: Line 1:
=Using the JFILE:: class=
+
{{version|1.5,2.5,3.x}}
 +
=Using the JFile:: class=
  
There are 4 classes in the J15 filesystem library.
+
There are 4 classes in the filesystem library.
  
 
* JFile:: (file.php)
 
* JFile:: (file.php)
 
* JFolder:: (folder.php)
 
* JFolder:: (folder.php)
 
* JPath:: (path.php)
 
* JPath:: (path.php)
* JArchive:: (archive.php)[/i]
+
* JArchive:: (archive.php)
  
For this first tutorial, I will focus on the JFile:: class.
+
This tutorial focuses on the JFile:: and JFolder:: classes.
  
The base for filehandling is the JFile class, found in libraries/joomla/filesystem/file.php
+
The base for file handling is the JFile class, found in the ''/libraries/src/Filesystem/File.php'' file.
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.
+
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 file extension==
+
==Get the File Extension==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
Line 21: Line 22:
 
Pretty clear, just feed the function with a filename and it will return the extension of the file you selected.
 
Pretty clear, just feed the function with a filename and it will return the extension of the file you selected.
  
==Strip file extension==
+
==Strip the File Extension==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
Line 28: Line 29:
 
This will return the filename without the extension.
 
This will return the filename without the extension.
  
==Clean filename==
+
==Clean the Filename==
 +
Use:
 +
It cleans out all odd characters from a filename and returns a safe filename.
 +
 
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
$safefilename = JFile::makeSafe($filename);
+
$safefilename = File::makeSafe($filename);
 +
</source>
 +
 
 +
 
 +
REQUIRES:
 +
<source lang=php>
 +
use Joomla\CMS\Filesystem\File;
 
</source>
 
</source>
It cleans out all odd characters from a filename and returns a safe filename.
+
<i>Normally at the head of the file.<i>
  
==Copy a file==
+
==Copy a File==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFile::copy($src, $dest);
 
JFile::copy($src, $dest);
 
</source>
 
</source>
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.
+
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==
+
==Delete a File==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFile::delete($path.$file);
 
JFile::delete($path.$file);
 
</source>
 
</source>
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.
+
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==
+
==Upload a File==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFile::upload($src, $dest);
 
JFile::upload($src, $dest);
 
</source>
 
</source>
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.
+
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==
 
==Example==
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.
+
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.
+
The script is fired from an upload form. That form has a file element, called file_upload (see below).
 +
<source lang=php>
 +
<form name="upload" method="post" enctype="multipart/form-data">
 +
<input type="file" name="file_upload" />
 +
<input type="submit" />
 +
</form>
 +
</source>
 +
 
 +
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:
 
<source lang=php>
 
<source lang=php>
 
<?php
 
<?php
***********************
+
/*
*                    *
+
* File upload example
* File upload example *
+
*/
*                     *
+
// Retrieve file details from uploaded file, sent from upload form
***********************
+
$file = JFactory::getApplication()->input->files->get('file_upload');
//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
+
// Import filesystem libraries. Perhaps not necessary, but does not hurt.
 
jimport('joomla.filesystem.file');
 
jimport('joomla.filesystem.file');
  
//Clean up filename to get rid of strange characters like spaces etc
+
// Clean up filename to get rid of strange characters like spaces etc.
 
$filename = JFile::makeSafe($file['name']);
 
$filename = JFile::makeSafe($file['name']);
  
//Set up the source and destination of the file
+
// Set up the source and destination of the file
 
$src = $file['tmp_name'];
 
$src = $file['tmp_name'];
 
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
 
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
  
//First check if the file has the right extension, we need jpg only
+
// First verify that the file has the right extension. We need jpg only.
if ( strtolower(JFile::getExt($filename) ) == 'jpg') {
+
if (strtolower(JFile::getExt($filename)) == 'jpg')  
   if ( JFile::upload($src, $dest) ) {
+
{
       //Redirect to a page of your choice
+
  // TODO: Add security checks.
   } else {
+
 
       //Redirect and throw an error message
+
   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
+
else
 +
{
 +
   // Redirect and notify user file does not have right extension.
 
}
 
}
 
?>
 
?>
 
</source>
 
</source>
  
=Using the JFolder:: class=
+
=Using the JFolder:: Class=
The base for folder handling is the JFolder class, found in libraries/joomla/filesystem/folder.php
+
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 of this post, I put it together in a very simple script as an exmaple
+
Below I will discuss the most common options from this library file. At the end there is a simple example script.
  
==Copy folder==
+
==Copy Folder==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::copy($src, $dest, $path, $force);
 
JFolder::copy($src, $dest, $path, $force);
 
</source>
 
</source>
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.
+
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==
+
==Create Folder==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::create($path, $mode);
 
JFolder::create($path, $mode);
 
</source>
 
</source>
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.
+
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==
 
==Move folder==
Line 116: Line 144:
 
JFolder::move($src, $dest);
 
JFolder::move($src, $dest);
 
</source>
 
</source>
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.
+
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==
+
==Check If a Folder Exists==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::exists($path);
 
JFolder::exists($path);
 
</source>
 
</source>
Wrapper for the php is_dir() function. Pretty straightforward, returns true if folder exists.
+
Wrapper for the PHP ''is_dir()'' function. Returns true if the folder exists.
  
==Read files from folder==
+
==Read Files from a Folder==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::files($path, $filter = '.', $recurse, $fullpath , $exclude);
 
JFolder::files($path, $filter = '.', $recurse, $fullpath , $exclude);
 
</source>
 
</source>
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.
+
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==
+
==Read Folders from Filesystem==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::folders($path, $filter = '.', $recurse, $fullpath , $exclude);
 
JFolder::folders($path, $filter = '.', $recurse, $fullpath , $exclude);
 
</source>
 
</source>
Exactly the same as JFolder::files(), except this does only return an array with foldernames.
+
The same as ''JFolder::files()'', except this only returns an array with folder names.
  
==Make a tree like list from a folder structure==
+
==Make a Tree-Like List from a Folder Structure==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::listFolderTree($path, $filter, $maxLevel = 3, $level = 0, $parent = 0);
 
JFolder::listFolderTree($path, $filter, $maxLevel = 3, $level = 0, $parent = 0);
 
</source>
 
</source>
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:
+
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:
 
<source lang=php>
 
<source lang=php>
 
Array
 
Array
Line 177: Line 205:
 
</source>
 
</source>
  
==Clean a path string==
+
==Clean a Path String==
 
Syntax:
 
Syntax:
 
<source lang=php>
 
<source lang=php>
 
JFolder::makeSafe($path);
 
JFolder::makeSafe($path);
 
</source>
 
</source>
Identically to the JFile::makeSafe() function. It cleans all odd characters out of the string and returns a clean path.
+
Similar to the ''JFile::makeSafe()'' function. It cleans all odd characters out of the string and returns a clean path.
  
 
==Example==
 
==Example==
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.
+
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.
 
<source lang=php>
 
<source lang=php>
 
<?php
 
<?php
//First we set up parameters
+
// First we set up parameters.
$searchpath = JPATH_COMPONENT . DS . "images";
+
$searchpath = JPATH_COMPONENT . '/images';
  
//Then we create the subfolder called jpg
+
// Import the folder system library.
if ( !JFolder::create($searchpath . DS . "jpg") ) {
+
jimport('joomla.filesystem.folder');
   //Throw error message and stop script
+
 
 +
// 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.
+
// Now we read all jpg files and put them in an array.
$jpg_files = JFolder::files($searchpath, '.jpg');
+
$jpgFiles = JFolder::files($searchpath, '.jpg');
  
//Now we need some stuff from the JFile:: class to move all files into the new folder
+
// Now we need some stuff from the ''JFile:: class'' to move all the files into the new folder.
foreach ($jpg_files as $file) {
+
foreach ($jpgFiles as $file)
   JFile::move($searchpath. DS . $file, $searchpath . DS. "jpg" . $file);
+
{
 +
   JFile::move($searchpath . '/' . $file, $searchpath . '/' . 'jpg' . $file);
 
}
 
}
  
//Lastly, we are moving the complete subdir to the root of the component.
+
// Last we move the complete subdir to the root of the component.
if (JFolder::move($searchpath . DS. "jpg", $JPATH_COMPONENT) ) {
+
if (JFolder::move($searchpath . '/'. 'jpg', JPATH_COMPONENT))
   //Redirect with perhaps a happy message
+
{
} else {
+
   // Redirect with perhaps a happy message.
   //Throw an error
+
}
 +
else
 +
{
 +
   // Throw an error.
 
}
 
}
 
?>
 
?>
 
</source>
 
</source>
  
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.
+
<noinclude>[[Category:Development]]</noinclude>

Latest revision as of 03:10, 9 December 2019

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.
}
?>