About Lesson
Download a file and Copy a file:
To download a file or copy a file in PHP, you typically work with the filesystem and utilize appropriate headers for file downloads. Below are explanations and examples for both operations:
Download a File:
To enable users to download a file from your server, you need to send the file to the client with the appropriate headers.
PHP
<?php
$file = 'example.txt';
// Set headers for file download
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
readfile($file);
?>
- Replace ‘example.txt’ with the path to the file you want to download.
- This code sets the appropriate headers for a file download, specifying the file’s MIME type and attachment disposition.
- readfile() sends the file contents to the client for download.
Copy a File:
To copy a file from one location to another in PHP, you can use the copy() function.
PHP
<?php
$sourceFile = 'source.txt';
$destinationFile = 'destination.txt';
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully.";
} else {
echo "Failed to copy file.";
}
?>
- Replace ‘source.txt’ with the path to the source file.
- Replace ‘destination.txt’ with the path to the destination where you want to copy the file.
- The copy() function returns true on success and false on failure.
Make sure your PHP script has the necessary permissions to read the source file and write to the destination file. Also, ensure that the paths provided are correct.
These operations allow you to handle file downloads and copying files in PHP applications, providing users with access to files or facilitating file management tasks.