How can I change a files extension using PHP?
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.
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.
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
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);
}
}