views:

2850

answers:

5

How can I change a files extension using PHP?

+5  A: 

http://www.php.net/rename

Galen
What if you're using a variable as the file name?
PHLAK
The function takes strings, it doesn't matter if those strings are string literals or string variables.
David Dorward
+3  A: 

Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:

function replace_extension($filename, $new_extension) {
    return preg_replace('/\..+$/', '.' . $new_extension, $filename);
}

Then use the rename() function to rename the file with the new filename.

yjerem
A: 

I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:

// Converts image file extensions to all lowercase
$currentdir = opendir($gallerydir);
while(false !== ($file = readdir($currentdir))) {
  if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {
    $srcfile = "$gallerydir/$file";
    $filearray = explode(".",$file);
    $count = count($filearray);
    $pos = $count - 1;
    $filearray[$pos] = strtolower($filearray[$pos]);
    $file = implode(".",$filearray);
    $dstfile = "$gallerydir/$file";
    rename($srcfile,$dstfile);
  }
}

This worked for my purposes.

PHLAK
A: 

In one of my project, there was a requirement for extension conversion. I used glob() and rename() functions for this purpose.

http://khumlo.com/web-developer/how-to-change-file-extension-using-php.html

fernando
Note that this site 404s now.
therefromhere
A: 

Hi Guys I have a problem with this I need to rename the file extension after i moved the (unknown) uploaded file to several places, I need to rename the .MP3 extension to .zip please have a look at my whole peice of code and please tell me what I need to do to make it work because this has me now for 2 days and i wanna pull my hair out. thanx in advance/////////

///////////////////this is where i need to change the extension/////////////////////////

$filename = "members/$id/music" . "/" . $_FILES["file"]["name"];

function replace_extension($filename, $zip) {
return preg_replace('/\..+$/', '.' . $zip, $filename);

}

}

drakos
Please don't post questions in the answer section like this - instead post a new question (and maybe link back to this related question).
therefromhere