Issue uploading image in Joomla PHP

628 views Asked by At

I am using Joomla and created Image Gallery for K2 Component. I want to upload image into my gallery, and used for away from garbage name i used $fileName = preg_replace('/[^\w\._]+/', '_', $fileName); by this i can upload images with "- (dash)"in them but it creates problem while uploading images with "whitespace" in them and gives error.

 **JFile: :copy: Cannot find or read file: $/opt/lampp/htdocs/joomla_2.5/images/folkgallery/tmp/14 .jpg**

When I remove the above code preg_match then i can upload images with whitespace in them but not able to upload images with -(dash)in them. So kindly provide some way that I can upload image with anytype of image name it contains.

1

There are 1 answers

0
Pep Lainez On

Add a \s on your regular expfession to match the space.

[^\w\s._]

Edit: with more testing, i think that this expression is enough for your needs:

preg_replace('/[_|\s]+/i', '-', 'fil ename_1.jpg');

will produce

fil-ename-1.jpg

But, for Joomla, I bet it's better to use this (as it is told here: http://docs.joomla.org/Secure_coding_guidelines#File_uploads)

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

jimport('joomla.filesystem.file');
$file['name'] = JFile::makeSafe($file['name']);

if (isset( $file['name'] )) {
    $filepath = JPath::clean( $somepath.'/'.strtolower( $file['name'] ) );
    JFile::upload( $file['tmp_name'], $filepath );
}

The link is outdated (JRequest is deprecated and it is recommended to use JInput) but it solves your problem.

Regards