Categories
PHP

Copying, Moving and Deleting Files

Learn how to rename, move, copy or delete files in PHP.

copy() – copying files

<?php
 //Syntax
 copy(string $from, string $to, ?resource $context = null): bool

The copy functoin makes a copy of the file source to the destination and accepts three parameters:

  1. $from path to source file
  2. $to the destination path
  3. $context stream_context_create() resource

Example: Copy a file from one directory to another

This function returns true if successful and false on failure.

<?php
 $from = 'file.txt';
 $to = 'uploads/abc.txt';
 if ( copy($from, $to) )
  echo "The file $from copied to $to.";
 else
  echo 'Error';
 //Prints: The file file.txt copied to uploads/abc.txt.

rename() – moving and renaming files

<?php
 //Syntax
 rename(string $from, string $to, ?resource $context = null): bool
  1. $from path to source file
  2. $to the destination path
  3. $context a stream context

The rename function renames the old file name to a new name, it overwrites the existing file if the new name already exists.

Example: Renaming files

The rename() function returns true if successful and false on failure.

<?php
 $old_name = 'file.txt';
 $new_name = 'abc.txt';
 if ( rename($old_name, $new_name) )
  echo "The $old_name renamed to $new_name.";
 else
  echo 'Error';
 //Prints: The file.txt renamed to abc.txt.

Example: Moving files to the new location

You can also use the rename() function to move a file across directories. By renaming the file to have a different path, you can move the file:

<?php
 $old_name = 'images/front.jpg';
 $new_name = 'uploads/logo.jpg';
 if (  rename ($old_name, $new_name) )
  echo 'File moved to the new location and renamed';
 else
  echo 'Error';
<?php
 //Syntax
 unlink(string $filename, ?resource $context = null): bool

The unlink function deletes a file and it accepts two parameters:

  1. filename with path
  2. context a stream context

The unlink() function returns true if successful and false on failure.

Example: Deleting files

<?php
 if ( unlink('file.txt') )
  echo 'The file.txt has been deleted.';
 else
  echo 'Error';

Working with Files in PHP: