Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to copy or move a file

Short answer

copy() makes a copy, rename() moves or renames:

<?php
 
$dir = sys_get_temp_dir();
file_put_contents($dir . '/recipe-a.txt', 'data');
 
copy($dir . '/recipe-a.txt', $dir . '/recipe-b.txt');
rename($dir . '/recipe-b.txt', $dir . '/recipe-c.txt');
 
var_dump(is_file($dir . '/recipe-a.txt'), is_file($dir . '/recipe-b.txt'), is_file($dir . '/recipe-c.txt'));

Output:

bool(true)
bool(false)
bool(true)

Check the result

Both functions return false when the operation fails — for instance, without write permission. An existing destination file is replaced without asking.

Functions used in this recipe

  • copy — Copies a file.
  • rename — Renames or moves a file.
  • unlink — Deletes a file.

Thanks for reading!

Donate to the site — we work hard for you.