rename uploaded file if has a space in it

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
Blondy
Forum Commoner
Posts: 32
Joined: Thu Mar 06, 2008 5:55 pm

rename uploaded file if has a space in it

Post by Blondy »

hi guys I has written a script to resize uploaded images
but I've a problem with images has a space in it's name
how I can detect if the file has a space in it's name or not
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: rename uploaded file if has a space in it

Post by John Cartwright »

Code: Select all

if (strstr('does this have a space in it?', ' ')) {
   echo 'yes';
}
 
Otherwise, you can simple pass all your filenames through a str_replace(),

Code: Select all

 
$filename = str_replace(' ', '', $filename);
 
Blondy
Forum Commoner
Posts: 32
Joined: Thu Mar 06, 2008 5:55 pm

Re: rename uploaded file if has a space in it

Post by Blondy »

thanks,
can you help me create a loop to find an available name for saving afile
something like this

Code: Select all

if(file_exist($filename){
while (file_exist("$filename){
$count=$count+1;
$filename="".$filename."".$count."";
}}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: rename uploaded file if has a space in it

Post by John Cartwright »

It is usually better to store the md5 hash of the filename, to greatly reduce the number of namespace collissions. I then store the filename in the database relating to the md5 hash, which then allows us to have multiple files with the same (original) filename.

If you insist though, completely untested.

Code: Select all

 
$filename = 'checkexists.jpg'; //file we want to save with unique name
 
$extension = array_pop(explode('.', $filename)); //get the extension
$basefilename = basename($filename, '.'. $extension); //get filename without extension
$count = 0; 
 
do 
{
   $count += 1;   
   $checkfilename = $basefilename . $count .'.'. $extension //reassemble the filename
} 
while (file_exist($checkfilename));
 
echo $checkfilename;
 
Post Reply