PHP copy() | Copy 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 codes.txt file gets copied into cracker.txt file. If 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 copy() function in PHP, is:

copy(source, destination, context)

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

PHP Copy Content of One File to Another

<?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 above PHP example, is:

php copy file content

Note - The fopen() opens a file.

Note - The fclose() closes a file.

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

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

If you simplify 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 »