Download and rename file from Server using php script

為{幸葍}努か 提交于 2019-12-25 02:21:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!