PHP

Copying, Moving, and Deleting Files

copy($filename, $tempname1);
rename($tempname1, $tempname2);
unlink($tempname2);

Many other standard command-line functions of many operating systems are available in PHP. This not only includes chmod() and chgrp(), but also the following file system operations:

copy() function syntax

bool copy ( string $source , string $dest [, resource $context ] )

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

  1. source path to source file

  2. dest the destination path

  3. stream_context_create() resource

This function return true if successful and false on failure.

rename() function syntax

bool rename ( string $oldname , string $newname [, resource $context ] )

The rename function renames oldname to newname a file or directory and overwrite if newname already exists. This function accepts three parameters:

  1. oldname with path

  2. newname with path

  3. context a stream context

This function return true if successful and false on failure.

unlink() function syntax

bool unlink ( string $filename [, resource $context ] )

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

  1. filename with path

  2. context a stream context

This function return true if successful and false on failure.

The preceding code duplicates the current file, moves it (or renames it), and finally deletes the resulting file.

Example of Copying, Moving, and Deleting Files

<?php
  $filename = 'php.ini';
  $tempname1 = $filename . rand();
  $tempname2 = $filename . rand();
  copy($filename, $tempname1);
  echo "Copied to $tempname1<br />";
  rename($tempname1, $tempname2);
  echo "Moved to $tempname2<br />";
  unlink($tempname2);
  echo "File deleted.";
?>
by BrainBellupdated
Advertisement: