To copy a file in PHP, we can use the `copy()` function. This function allows us to create an exact copy of a file, including its content and permissions. The `copy()` function takes two parameters: the source file and the destination file.
The source file is the file we want to copy, and it is specified as a string representing the file path. This can be an absolute path or a relative path to the current working directory. The destination file is the file where we want to copy the contents of the source file. Like the source file, it is specified as a string representing the file path.
Here is the syntax of the `copy()` function:
php bool copy ( string $source , string $destination [, resource $context ] )
The `copy()` function returns a boolean value indicating whether the file copy was successful or not. It returns `true` on success and `false` on failure.
Let's look at an example to understand how to use the `copy()` function:
php
$sourceFile = 'path/to/source/file.txt';
$destinationFile = 'path/to/destination/file.txt';
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully.";
} else {
echo "Failed to copy the file.";
}
In this example, we have a source file located at `'path/to/source/file.txt'` and we want to copy its contents to a destination file located at `'path/to/destination/file.txt'`. The `copy()` function is called with the source and destination file paths as arguments. If the copy operation is successful, it will echo "File copied successfully." Otherwise, it will echo "Failed to copy the file."
It is important to note that the `copy()` function will overwrite the destination file if it already exists. If you want to avoid overwriting existing files, you can use the `file_exists()` function to check if the destination file exists before performing the copy operation.
The `copy()` function in PHP allows us to copy the contents of a file to another file. It takes the source file path and the destination file path as parameters and returns a boolean value indicating the success of the copy operation.
Other recent questions and answers regarding Examination review:
- What function can we use to rename a file in PHP?
- How can we find the absolute path of a file in PHP?
- How can we check if a file exists before performing operations on it in PHP?
- What is the purpose of the `readfile` function in PHP?

