Bootstrap FreeKB - PHP - Copy a file
PHP - Copy a file

Updated:   |  PHP articles

copy can be used to copy a file in PHP.

PHP is typically being run as the apache or www-data user, thus the apache or www-data user will need to have permission to copy the file. exec can be used to run the whoami command to determine if PHP is being run as apache or www-data.

<?php
  echo exec('whoami');
?>

 

And getcwd will return your present working directory.

<?php
  echo getcwd();
?>

 

For example, let's say you want to make a copy of the /var/www/html/foo.php file on a Linux system. In this example, the www-data user has rwx (read, write, execute) permissions to the foo.php, so the www-data user should be able to make a copy of the the foo.php file. The apache or www-data user will also need to have permission to the directory where the new file will reside.

~]$ ls -ld /var/www/html
drwxr-xr-x. 2 www-data  www-data  6 Feb  5 07:59 /var/www/html

 

Here is how you would make a copy of /var/www/html/foo.php.

copy("/var/www/html/foo.php", "/var/www/html/bar.php");

 

It's probably also a good idea to use the file_exists function to first ensure the file exists.

$current_file = ""/var/www/html/foo.php";
$new_file = "/var/www/html/bar.php";

if (!file_exists($current_file)) {
  if (!copy($current_file, $new_file)) {
    echo "failed to copy $current_file to $new_file <br />";
  }
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ecb2f5 in the box below so that we can be sure you are a human.