tags:

views:

429

answers:

5

How do I change a files file-extension name in php?

example: $filename='234230923_picture.bmp' and I want the extension to change to 'jpg'.

Thanks

+1  A: 

rename() the file, substituting the new extension.

Rob
A: 

You can use this to rename the file http://us2.php.net/rename and this http://us2.php.net/manual/en/function.pathinfo.php to get the basename of the file and other extension info..

Sam Ingrassia
+3  A: 

Just replace it with regexp:

$filename = preg_replace('"\.bmp$"', '.jpg', $filename);

You can also extend this code to remove other image extensions, not just bmp:

$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
Ivan Nevostruev
+8  A: 
$newname = basename($filename, ".bmp").".jpg";
rename($filename, $newname);

Remember that if the file is a bmp file, changing the suffix won't change the format :)

gnud
+1 for not misusing regex.
The Wicked Flea
A: 

Not using regex (like the basename example), but allowing multiple extension possibilities (like the regex example):

$newname = str_replace(array(".bmp", ".gif"), ".jpg", $filename);
rename($filename, $newname);

Of course any simple replace operation, while less expensive then regex, will also replace a .bmp in the middle of the filename.

As mentioned, this isn't going to change the format of a image file. To do that you would need to use a graphics library.

Tim Lytle