July 1, 2010
PHP change file extension
Question by Kyle
I am trying to change a file exenstion, but whenever I do the file seems to corrupt.
$oldFileName = $targetDir . DIRECTORY_SEPARATOR . $fileName;
$newString = preg_replace('".tmp$"', '.jpg', $oldFileName);
rename($oldFileName, $newString);
The code works and changes the extension, but yet the file when downloaded, comes up as being corrupt.
The exension is .tmp and I am trying to change it to .jpg.
If I download the .tmp and manually change it to a .jpg it works, but not when the PHP does it.
Anyone know why this may be happening?
Thanks!
Answer by Starx
try this
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak'; //new file with extension
if (!copy($file, $newfile)) {
echo "failed to copy $file...n";
}
?>