Check for dots in the filename?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Check for dots in the filename?

Post by Sindarin »

In my image upload form, I noticed that uploading an image with dots in the filename, causes my GD thumbnail generation code to crash because the filename is not parsed correctly. I tried str_replace but it replaces all the dots including the extension one. I tried filtering with basename, with no result. How can I remove all the dots from the filename excluding the extension one?
User avatar
it2051229
Forum Contributor
Posts: 312
Joined: Tue Dec 25, 2007 8:34 pm

Re: Check for dots in the filename?

Post by it2051229 »

most extensions are found at the end of the file name so do something like this

1] do split the file name according to dots

Code: Select all

 
$splittedFileName = explode(".", $filename);
 
2] note that at the end of the splitted file name is the extension of the file name

Code: Select all

 
// note that the dots are gone.
for($i=0; $i < count($splittedFileName); $i++)
{
       if($i == count($splittedFileName)-1)
       {
            $newFilename = $newFilename.".".$splittedFileName[$i];
       }
       else
       { 
          $newFilename = $newFileName.$splittedFileName[$i];
       }
}
 
Last edited by it2051229 on Mon Aug 25, 2008 7:00 am, edited 1 time in total.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Check for dots in the filename?

Post by onion2k »

Sindarin wrote:In my image upload form, I noticed that uploading an image with dots in the filename, causes my GD thumbnail generation code to crash because the filename is not parsed correctly. I tried str_replace but it replaces all the dots including the extension one. I tried filtering with basename, with no result. How can I remove all the dots from the filename excluding the extension one?
Rather than trying to change the filename so it works with your code, why not fix the code so it can handle filenames with lots of dots in them? I call my images things like company.whitelogo.320x240.png. I'd be pretty annoyed if I uploaded one and it got changed to something else.
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Check for dots in the filename?

Post by Sindarin »

most extensions are found at the end of the file name so do something like this
indeed the dots are gone but again, the extension is gone as well. :(


Can someone please tell me how to detect if dots exist in the filename and then echo a warning?
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: Check for dots in the filename?

Post by Stryks »

I'd have to second the idea of changing your code to allow the filenames.

What error does it throw? Can you post some code from where it fails? It may just be an easy fix.

I mean ... if you want to split filename from extension, you can just go ...

Code: Select all

$file_parts = pathinfo('my.file.is.cool.txt');
 
echo "File name=" . $file_parts['filename'] . "<br>Extension = " . $file_parts['extension'];
 
// Produces
// File name = my.file.is.cool
// Extension = txt
 
Just my two cents anyhow.

Cheers
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Check for dots in the filename?

Post by Sindarin »

Code: Select all

//Maximum file size.
$MAX_SIZE = 5000000;
$max_kbs = $MAX_SIZE/1000;
$max_width = 11220;
$max_height = 11220;
 
//valid extensions
$FILE_EXTS  = array('.jpg','.png','.gif');
$file_extensions='.jpg , .png , .gif';
 
//load functions
require_once('inc/functions.php');
 
switch($_GET['file']){
case 'upload':
 
// UPLOAD FILE
 
//Get server paths
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
 
$upload_dir = "files/uploads/images/";
$upload_url = $url_dir."/files/";
 
//get file name
$file_name = $_FILES['userfile']['name'];
$temp_name = $_FILES['userfile']['tmp_name'];
$file_size = $_FILES['userfile']['size'];
$file_path = $upload_dir.$file_name;
list($width, $height, $type, $attr) = getimagesize($temp_name);
$file_ext = strtolower(substr($file_name,strrpos($file_name,".")));
$file_size_kbs=$file_size/1000;
 
 
//replace illegal characters
$file_name = str_replace("\\","",$file_name);
$file_name = str_replace("'","",$file_name);
//IF I DO $file_name = str_replace(".","",$file_name); HERE THERE WILL BE ERRORS FROM GD LIBRARY AS THE EXTENSION DOT GETS WIPED OUT AS WELL.. :(
 
//Check if file exists
 
$file_to_check="files/uploads/images/$file_name";
if (file_exists($file_to_check) && !$file_name=="")
{
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ?? ?????? <b>$file_name</b> ??? ???????! ???????? ??????? ?? ????? ??? ???????????????!</center>";
}
else
{
 
//Check file name length
if (strlen (basename(($file_name))) > 50)
{
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ?? ????? ?? ??????? ????? ???? ??????, ????? 50 ?????????? ????????????!</center>";
}
else
{
 
//Check file name
if ($file_name == "")
{
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ??? ?????????? ??????!</center>";
}
else
{
 
 
//File Dimensions Check
if( $width > $max_width || $height > $max_height) 
 {
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ?? ????: $height ??? ??????: $width ??? ??????? ????? ?????????? ??? ?? ????????????! ($max_width x $max_height).</center>";
}
else
{
 
//File Size Check
if( $file_size > $MAX_SIZE) 
 {
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ?? ??????? ??? ???????: ($file_size_kbs Kbs) ????? ?????????? ??? ?? ???? ($max_kbs Kbs).</center>";
}
else
{
 
//File type Check
     if (!in_array($file_ext, $FILE_EXTS))
  {
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ? ????? ??? ??????? ??? ???????????.</center>";
}
else
{
 
//make upload entry
$db_insert="INSERT INTO images (image_id,image_src,image_alt)
VALUES
('i++','$file_name','image')";
 
if (!mysql_query($db_insert,$db_connection))
  {
  die("<font color='red'><img src='files/images/layout/cms-error.png' />Error</font>: " . mysql_error());
  }
 
//fileupload
$result  =  move_uploaded_file($temp_name, $file_path);
if ($result==1)
{
//$delim="...";
//$file_name=trim_letters($file_name,40,$delim);
echo "<center><img src='files/images/layout/cms-ok.png' border=0 alt='Success' /><font color='green'>?? ?????? <b>$file_name</b> ??????? ??? server ?? ????????!</font> | ??????????: $width x $height pixels | ??????? ?? Kb: $file_size_kbs</center>";
 
//START THUMBNAIL
function createthumb($name,$filename,$new_w,$new_h){
    $system=explode('.',$name);
    if (preg_match('/jpg|jpeg/',$system[1])){
        $src_img=imagecreatefromjpeg($name);
    }
    if (preg_match('/png/',$system[1])){
        $src_img=imagecreatefrompng($name);
    }
    $old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
    $thumb_w=$new_w;
    $thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
    $thumb_w=$old_x*($new_w/$old_y);
    $thumb_h=$new_h;
}
if ($old_x == $old_y) {
    $thumb_w=$new_w;
    $thumb_h=$new_h;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
    
    if (preg_match("/png/",$system[1]))
{
    imagepng($dst_img,$filename); 
} else {
    imagejpeg($dst_img,$filename); 
}
imagedestroy($dst_img); 
imagedestroy($src_img); 
}
//do it
$filename="files/uploads/images/$file_name";
$thumbname="files/uploads/images/thumbnails/$file_name";
createthumb($filename,$thumbname,100,100);
 
//END OF THUMBNAIL
 
}
else
{
echo "<center><img src='files/images/layout/cms-error.png' border=0 alt='Error' /><font color='red'>Error</font>: ?? ?????? ??? ??????? ?? ?????? ???? server!</center>";
exit;
}
}
}
}
}
}
}
  break;
I am guessing the errors would be somewhere after the //START THUMBNAIL code as I copy/pasted php.net snippet of it, but it confuses me a bit.

The errors produced are:
Warning: imagesx(): supplied argument is not a valid Image resource in C:\xampp\htdocs\quicksilver2\news.php on line 155

Warning: imagesy(): supplied argument is not a valid Image resource in C:\xampp\htdocs\quicksilver2\news.php on line 156

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\xampp\htdocs\quicksilver2\news.php on line 170

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\xampp\htdocs\quicksilver2\news.php on line 179
when I try to upload a file with a dot in the filename. The file successfully uploads but the thumbnail is not generated.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: Check for dots in the filename?

Post by Stryks »

Well .. lets take a shot in the dark here.

Comment out line 33 and insert

Code: Select all

$file_parts = pathinfo('my.file.is.cool.txt');
$file_ext = strtolower($file_parts['extension']);
You can also comment out line 38 and 39.

Then we need to alter that thumbnailer. We could either change the function, or duplicate a bit of code. I personally would favor passing the extension we have already found.

So ... modify line 112 and comment out through to 119 so that it reads ...

Code: Select all

function createthumb($name,$filename,$filetype,$new_w,$new_h){
   if(($filetype === 'jpg') || ($filetype === 'jpeg')) $src_img=imagecreatefromjpeg($name);
   if($filetype === 'png') $src_img=imagecreatefrompng($name);
 
Then line 139 should be ...

Code: Select all

if($filetype === 'png')
You should be able to call it then on line 149 with ...

Code: Select all

createthumb($filename,$thumbname,$file_ext,100,100);
Actually .. now that I think about it, it's kinda ambitious ... trying to recode something after a glance ... but hey ... the worst that can happen is that it doesn't work.

Give it a try and ... yeah ... let me know what bits I messed up on. :lol:

Cheers
Post Reply