[TUTORIAL] File handling in J15

Submit your own tutorials, guides and API documents for inclussion in the Official Developer Documentation.
Post Reply
rsgallerydude
Joomla! Intern
Joomla! Intern
Posts: 69
Joined: Sat Sep 03, 2005 7:35 pm
Location: Netherlands
Contact:

[TUTORIAL] File handling in J15

Post by rsgallerydude » Sun Oct 21, 2007 5:54 pm

Hi,

The last few weeks I am rewriting RSGallery2 to use the filesystem libraries, provided by Joomla. I learned a lot doing that and I'd like to share this with the community.

Filehandling in Joomla 1.5

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
Syntax:

Code: Select all

$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
Syntax:

Code: Select all

$name = JFile::stripExt($filename);
This will return the filename without the extension.

Clean filename
Syntax:

Code: Select all

$safefilename = JFile::makeSafe($filename);
It cleans out all odd characters from a filename and returns a safe filename.

Copy a file

Syntax:

Code: Select all

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
Syntax:

Code: Select all

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
Syntax:

Code: Select all

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

Code: Select all

<?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
}
?>
Obviously there is a lot more you can do with this script, but it gives a general idea of it's use.

Good luck using the JFile library.

Cheers,

Ronald
Last edited by rsgallerydude on Wed Nov 07, 2007 6:04 pm, edited 1 time in total.

rsgallerydude
Joomla! Intern
Joomla! Intern
Posts: 69
Joined: Sat Sep 03, 2005 7:35 pm
Location: Netherlands
Contact:

Re: [TUTORIAL] File handling in J15

Post by rsgallerydude » Mon Oct 22, 2007 7:21 am

Folder handling in Joomla 1.5

There are 4 classes in the J15 filesystem library.
  • JFile:: (file.php)
  • JFolder:: (folder.php)
  • JPath:: (path.php)
  • JArchive:: (archive.php)
For this second tutorial, I will focus on the JFolder:: class.

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
Syntax:

Code: Select all

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

Syntax:

Code: Select all

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
Syntax:

Code: Select all

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
Syntax:

Code: Select all

JFolder::exists($path);
Wrapper for the php is_dir() function. Pretty straightforward, returns true if folder exists.

Read files from folder

Syntax:

Code: Select all

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
Syntax:

Code: Select all

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
Syntax:

Code: Select all

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
Syntax:

Code: Select all

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

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.

Code: Select all

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

Good luck using JFolder.

Cheers,

Ronald
Last edited by rsgallerydude on Mon Oct 22, 2007 7:24 am, edited 1 time in total.

User avatar
Tonie
Joomla! Master
Joomla! Master
Posts: 16584
Joined: Thu Aug 18, 2005 7:13 am

Re: [TUTORIAL] File handling in J15

Post by Tonie » Mon Oct 22, 2007 7:28 am

Thanks for these :). I will post a link on the Joomla 101 coding group as well with these.

User avatar
Livingstone
Joomla! Intern
Joomla! Intern
Posts: 64
Joined: Sat Apr 07, 2007 6:28 pm
Location: UK
Contact:

Re: [TUTORIAL] File handling in J15

Post by Livingstone » Tue Jun 17, 2008 5:17 pm

JFile still contains alot of issues with permission in J1.5.3 especially when working with windows!

Still looking into exaclty whats goin on with that class and ill post back with specifics and reproducibility! but basically move(), copy(), delete() dont work! for me! but php inbuild copy() does! :eek:
Powerful & FREE! social networking for Joomla! Check it out

User avatar
jiggliemon
Joomla! Intern
Joomla! Intern
Posts: 81
Joined: Wed Nov 22, 2006 6:18 am
Contact:

Re: [TUTORIAL] File handling in J15

Post by jiggliemon » Sun Jul 20, 2008 6:05 am

I cadded a function to my class to suport the removal of spaces.

Code: Select all

	/*
	 * Replace Spaces with _
	 */
	function removeSpace($file) {
		$file = str_replace(array(' ', '-'), array('_','_'), $file);
		return $file;
	}

egggeek
Joomla! Fledgling
Joomla! Fledgling
Posts: 3
Joined: Fri May 30, 2008 8:10 am

Re: [TUTORIAL] File handling in J15

Post by egggeek » Mon Aug 18, 2008 1:23 pm

It's worth mentioning that the form you submit must have

Code: Select all

<form ... enctype="multipart/form-data">

User avatar
Marieke92
Member of the Month!
Member of the Month!
Posts: 95
Joined: Thu Nov 29, 2007 6:36 pm
Location: Hoorn, Netherlands

Re: [TUTORIAL] File handling in J15

Post by Marieke92 » Tue Aug 19, 2008 7:06 pm

Perhaps you could add this to http://docs.joomla.org/ ? Thanks :)
Greetz, Marieke
Joomla! Documentation Working Group | Joomla! Bug Squad Member | Joomla! Development Working Group
1.6 Help Screen Project Leader
Joomla!Community (Dutch Community) Documentation Team leader

rsgallerydude
Joomla! Intern
Joomla! Intern
Posts: 69
Joined: Sat Sep 03, 2005 7:35 pm
Location: Netherlands
Contact:

Re: [TUTORIAL] File handling in J15

Post by rsgallerydude » Sat Dec 20, 2008 2:41 pm

Marieke92 wrote:Perhaps you could add this to http://docs.joomla.org/ ? Thanks :)
Marieke,

Didn't check this thread for months.
I put up the tutorials at http://docs.joomla.org/How_to_use_the_f ... em_package

My Wiki skills are limited, so let me know if I need to make changes or adjustments.

Cheers,

Ronald

User avatar
Marieke92
Member of the Month!
Member of the Month!
Posts: 95
Joined: Thu Nov 29, 2007 6:36 pm
Location: Hoorn, Netherlands

Re: [TUTORIAL] File handling in J15

Post by Marieke92 » Sun Dec 21, 2008 10:03 am

It looks great!

Thanks a lot :)

Marieke
Greetz, Marieke
Joomla! Documentation Working Group | Joomla! Bug Squad Member | Joomla! Development Working Group
1.6 Help Screen Project Leader
Joomla!Community (Dutch Community) Documentation Team leader


Post Reply

Return to “Submit”