Copy a file from one directory to another in PHP

In this article, we will explain to you how to copy a file from one directory to another in PHP. In the upcoming articles, we’ll also show you how to rename, move or delete a file using PHP.

Copy a file using PHP

Using the built-in function copy(), we can copy a file in the same directory or one to another directory. It’s a very simple and easy way to copy a file using PHP.

This function requires two required arguments: the first one is the source path (A file path of file which wants to be copied) and second one is the destination path (A file path where copy a file). The copy() function returns a true on success otherwise false as a boolean value.

Note: If the source file already exists in the destination folder then it will be overwritten.

Let’s check the syntax and simple examples.

Syntax

Parameters

  • $source: It specifies the file path that you want to copy.
  • $destination: It specifies the file path where you want to copy.
  • $context: This is an optional parameter. It specifies the context resource created with the stream_context_create() function.

Example 1: Copy a file in the same directory

In the following example, we will see how to copy a file named file1.txt to file2.txt in the same directory.

Example 2: Copy a file from one directory to another.

In this second example, we will copy a file from one directory to another directory. The code for both examples is the same, only the paths are different.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *