Are there any specific PHP functions or methods that can be used to efficiently handle file uploads and downloads?
Handling file uploads and downloads efficiently in PHP can be achieved using the built-in functions `move_uploaded_file()` for uploads and `readfile()` for downloads. These functions are commonly used to handle file transfers securely and efficiently.
// File upload
if(isset($_FILES['file'])){
$file = $_FILES['file'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_file)){
echo "File uploaded successfully.";
} else{
echo "Error uploading file.";
}
}
// File download
$file_path = "path/to/file.txt";
if(file_exists($file_path)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else{
echo "File not found.";
}
Keywords
Related Questions
- What are the advantages and limitations of using DataTables for displaying filtered data in PHP?
- How can CSS be utilized instead of HTML tags like center and br for better code structure?
- How can a Unix time value stored in a MySQL database be converted into a readable date format for display in a table using PHP?