PHP creating, moving, copying and deleting files

PHP creating, moving, copying & deleting files

Copy files: Copies files from “source” to “destination”. If the destination file exists it will be overwritten. it returns true on success.

Syntax:
Bool copy (string $source, string $ dest);

Example:
Copy($file, $destfile)

Create files: fopen() is used for creating files. We need to pass the name of file it needs to open and the permission (read, write to that file).

Syntax:
resource fopen (string $filename, string $ mode);

Example:
$sample = fopen($sample, 'w') or die("can't open file");

Deleting files: unlink() function is used to delete files. The term “unlink” is used because one can think of these filenames as links that join the files to the directory you are currently viewing

Syntax:
unlink (string $filename);

Example:
unlink ($samplefile);

What is the difference between using copy() and move() function in php file uploading?

Copy() makes a copy of the file. It returns TRUE on success. It can copy from any source to destination. Move simple Moves the file to destination if the file is valid. While move can move the uploaded file from temp server location to any destination on the server. If filename is a valid upload file, but cannot be moved for some reason, no action will occur.

Write short note on copying files with copy() functions with an example

Copy () function copies a file. It returns true on success.
Syntax:
Copy(file, to file);

Example:
Echo Copy (“source.txt”,”dest.txt”);
Output:
1

If the destination file already exists, it will be overwritten.

Write short note on deleting files with unlink() with an example.

Unlink () is used to delete files. It returns true on success.

Syntax:
Unlink (filename, context);

Here, context is a set of options that can modify the behavior of streams.

Example:
<?php
    $file = "sample.txt";
    if (!unlink($file))
    {
        echo ("Error deleting $file");
    }
    else
    {
        echo ("Deleted $file");
    }
?>
Post your comment

You may like