PHP can only copy, rename or move files that are of the same owner with who is running the PHP script. After making sure of this, you can proceed to:
Copy a file to another place in PHP:
$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");
Rename a file and give it a new name:
$old = '/tmp/today.txt';
$new = '/tmp/tomorrow.txt';
rename($old, $new) or die("Unable to rename $old to $new.");
Move a file to a new place in PHP:
if (copy("/tmp/code.c","/usr/local/src/code.c")) {
unlink("/tmp/code.c");
}
Apparently you must make sure the copying is successful before doing the deletion.
Of course you can always execute a native Linux shell command such as ‘cp’ and ‘mv’ to do the dirty work for you instead of resorting to a PHP function. In this situation, you need the php function exec() to execute an external command.
You should also read:
- How to execute / run PHP scripts in the background?
- PHP: Compress Files into Tar or Zip – Make A Zip File or Tar File with PHP
- PHP: Differences between exec(), shell_exec(), system() and passthru()
- PHP: Delete File / Erase File / Remove File
- Essential SSH – 19 Linux SSH Commands You Simply Cannot Live Without


Facebook
Twitter
Google Plus
{ 6 comments… read them below or add one }
Hi, maybe you could help me with a problem i’m having, i need ti rename a file, with a specific name, how can i create a function that let do the following, if the file exist, rename the file with a new name like, document.php, document_2.php, document_3.php, document_4.php. i need to create a function to do that, when it renames a file rename it with the next number.
thank you
This is the simplist tutorial on file management iv’e seen so far.. Thanks for the help
Thanks for valuable information
Thank you! Copied your sample code and got it working immediately.
You can easy move files with rename: rename(“/tmp/code.c”,”/usr/local/src/code.c”)
its not working!!
its saying failed to open stream
help plzzz!
{ 1 trackback }