问题
I am storing all my files like "8asd98asd9as7d98asd9.file" and rerieve the "real" filename from a mysql-database: id (INT) AI PK, pathOnServer TEXT NOT NULL, realFilename VARCHAR(200) NOT NULL.
I need a script which allows me to access the files like "www.website.com/getFile?id=2" which downloads the file and renames it to "realFilename".
How can this be done?
回答1:
I do believe this code will do a trick you look for
<?php
if(!is_numeric($_GET['id'])) { // We validate parameter
echo 'Wrong parameter';
exit();
}
$oDb = new mysqli("ip","user","pass","databasename"); // Connecting to database
if($oDb->connect_errno) { // Check for an error
echo 'Error';
exit();
}
$oResult = $oDb->query('SELECT `pathOnServer`, `realFilename`
FROM --tablename--
WHERE id = '.(int)$_GET['id'].'
LIMIT 1'); // make query
if($oResult->num_rows != 1) {
echo 'No file found';
exit();
}
$oQuery = $oResult->fetch_object();
header('Content-disposition: attachment; filename='.$oQuery->realFilename); // put special headers
readfile($oQuery->pathOnServer.$oQuery->id); // put the file
?>
You could also add the header with filesize. Hope it will help you.
回答2:
You can use the Content-Disposition HTTP Header to tell the Browser the name of your file and then use readfile to load and echo said file.
header("Content-Type: application/octet-stream");
header('Content-Length: ' . filesize($path));
$name = basename($path);
header('Content-Disposition: attachment; filename="' . $name . '"');
readfile($path);
exit;
来源:https://stackoverflow.com/questions/23212225/download-and-rename-file-from-server-using-php-script