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]
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);
Strip file extension
Syntax:
Code: Select all
$name = JFile::stripExt($filename);
Clean filename
Syntax:
Code: Select all
$safefilename = JFile::makeSafe($filename);
Copy a file
Syntax:
Code: Select all
JFile::copy($src, $dest);
Delete a file
Syntax:
Code: Select all
JFile::delete($path.$file);
Upload a file
Syntax:
Code: Select all
JFile::upload($src, $dest);
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
}
?>
Good luck using the JFile library.
Cheers,
Ronald