[英]Download and rename file from Server using php script
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. 我存储我的所有文件,如“8asd98asd9as7d98asd9.file”,并从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". 我需要一个脚本,允许我访问“www.website.com/getFile?id=2”等文件,下载文件并将其重命名为“realFilename”。
How can this be done? 如何才能做到这一点?
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. 您可以使用Content-Disposition
HTTP Header告诉浏览器文件的名称,然后使用readfile加载和回显所述文件。
header("Content-Type: application/octet-stream");
header('Content-Length: ' . filesize($path));
$name = basename($path);
header('Content-Disposition: attachment; filename="' . $name . '"');
readfile($path);
exit;
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. 您还可以使用filesize添加标头。 Hope it will help you. 希望它会对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.