8

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

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

trejder
  • 17,148
  • 27
  • 124
  • 216
  • 1
    possible duplicate of [How to extract a file extension in PHP?](http://stackoverflow.com/questions/173868/how-to-extract-a-file-extension-in-php) – trejder Jul 20 '15 at 12:35

5 Answers5

26
$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
  • 77,584
  • 5
  • 64
  • 78
10

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
  • 28,143
  • 8
  • 66
  • 82
3

rename() the file, substituting the new extension.

trejder
  • 17,148
  • 27
  • 124
  • 216
Rob
  • 47,999
  • 5
  • 74
  • 91
3

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
  • 17,549
  • 10
  • 60
  • 91
-1

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
  • 115
  • 1
  • 14