PHP copy(): Copy the content of one file into another

The PHP copy() function is used when we need to copy the content of one file to another. For example:

<?php
   copy("codes.txt", "cracker.txt");
?>

The content of the codes.txt file gets copied into the cracker.txt file. If the cracker.txt file already contains some content, then it will get overwritten.

Note: The copy() function returns true on success and false on failure. For example:

<?php
   $source_file = "codes.txt";
   $target_file = "cracker.txt";
   
   if(copy($source_file, $target_file))
      echo "The content of $source_file is copied to $target_file";
   else
      echo "Unable to copy";
?>

PHP copy() Function Syntax

The syntax of the copy() function in PHP is:

copy(source, destination, context)

The third or last (context) parameter is optional and is used to specify a context resource created using the stream_context_create() function.

PHP Copy Content of One File to Another

The PHP code below is an example of how the "copy()" function can be used to copy files. In this example, the content before and after copying will be displayed.

<?php
   $source_file = "one.txt";
   $target_file = "two.txt";
   
   echo "<h1>Before Copy</h1>";
   echo "<p>---$source_file---</p>";
   $x = fopen($source_file, "r") or die("Unable to Open the File, $source_file");
   echo fread($x, filesize($source_file));
   fclose($x);
   echo "<p>---$target_file---</p>";
   $x = fopen($target_file, "r") or die("Unable to Open the File, $target_file");
   echo fread($x, filesize($target_file));
   fclose($x);
   
   if(copy($source_file, $target_file))
   {
      echo "<h1>After Copy</h1>";
      echo "<p>---$source_file---</p>";
      $x = fopen($source_file, "r") or die("Unable to Open the File, $source_file");
      echo fread($x, filesize($source_file));
      fclose($x);
      echo "<p>---$target_file---</p>";
      $x = fopen($target_file, "r") or die("Unable to Open the File, $target_file");
      echo fread($x, filesize($target_file));
      fclose($x);
   }
   else
      echo "<p>Unable to copy</p>";
?>

The output of the above PHP example is:

php copy file content

Note: The fopen() function opens a file.

Note: The fclose() function closes a file.

Note: The fread() function is used to read the content of an opened file using its pointer.

Note: The filesize() function returns the size of the specified file in bytes.

If you simplify the above PHP example, then it would be similar to:

<?php
   $source_file = "one.txt";
   $target_file = "two.txt";
   if(copy($source_file, $target_file))
      echo "<p>File copied successfully!</p>";
   else
      echo "<p>Unable to copy</p>";
?>

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!