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 common pitfalls when using the MySQL extension in PHP?
- How can SOAP or other web service protocols be used as a more secure alternative to including external code in PHP scripts?
- Is it possible to prevent PHP errors from being visible to regular users while still logging them for administrators?