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:
$from
path to source file$to
the destination path$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
$from
path to source file$to
the destination path$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';
unlink() – deleting files
<?php //Syntax unlink(string $filename, ?resource $context = null): bool
The unlink
function deletes a file and it accepts two parameters:
filename
with pathcontext
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:
- Returning or Downloading Files with an HTTP Request
- Reading a File into a String or Array
- PHP Opening and Closing Files
- Reading files by line or by character
- Writing and appending to files
- Reading and Writing CSV Files
- Parsing INI Files and Strings
- Check File Type (whether a file is a directory or a file)
- Understanding file Permissions in PHP
- Reading Information About Files in PHP
- Copying, Moving and Deleting Files in PHP
- Reading Directories Contents in PHP
- Browse directories recursively
- Zipping and Unzipping a File with Zlib and Bzip2
- Zip and Unzip Archives with ZipArchive
- Using Relative Paths for File Access