How to copy a file, and rename it as you go
TAGS: PHP, File, Copy, Rename


When you will like to copy a file, and maybe rename it at the same time, then you can use this very simple piece of code.
<?php
$sourcefile = 'file.txt';
$destinationfile = './backup/file.bak';
copy($sourcefile, $destinationfile)
?>

.. but I really like this next example, doing the error checking in same line as the Copy function, simply. It happens by checking 'if' there is an error with the copy. ('!' - meaning NOT), so if NOT copying (caused by an error), then send an error message to the screen.
<?php
$sourcefile = 'file.txt';
$destinationfile = './backup/file.bak';
if (!copy($sourcefile, $destinationfile)) {
    echo "Error trying to copy $sourcefile!";
}
?>