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";
}
?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!