Скачать переименованный файл с PHP - PullRequest
4 голосов
/ 19 января 2012

Я делаю PHP-скрипт, который загружает файл с указанием имени и версии.Файлы будут храниться на сервере следующим образом:

/dl/Project1/1.0.txt
/dl/Project1/1.1.txt
/dl/Project2/2.3.jar
/dl/Project2/2.3.1.jar

И пути для получения таких файлов будут выглядеть так:

download.php?name=Project1&type=txt&version=1.0
download.php?name=Project1&type=txt&version=1.1
download.php?name=Project2&type=jar&version=2.3
download.php?name=Project2&type=jar&version=2.3.1

Проблема возникает при фактической загрузке файлов.В этом примере я хочу, чтобы первые два файла загружались как Project1.txt, а последние два - как Project2.jar.Как я могу временно переименовать их, чтобы это работало?

Ответы [ 3 ]

6 голосов
/ 19 января 2012

Отправьте заголовок, определяющий имя файла.

$filename = $name . "." . $type;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

Я включил дополнительные заголовки, так как вы должны также отправить их. Это всего лишь модифицированный пример того, что вы можете увидеть в документации PHP на readfile.

2 голосов
/ 19 января 2012

Вам не нужно его переименовывать, вам просто нужно изменить имя в шапке, есть скрипт:

<?php
// Check is set all params
if (isset($_GET['name'], $_GET['type'], $_GET['version'])) {
  // Get the params into variables.

  // Secure replace to avoid the user downloading anyfile like @Kristian Antonsen said.
  // Replace all '..' to a single '.';
  $name = preg_replace('/[\.]{2,}/', '.', trim($_GET['name']));
  // Replace any strange characters.
  $type = preg_replace('/[^A-Za-z0-9]/', '', trim($_GET['type']));
  // Replace any letter and strange character.
  $version = preg_replace('/[^0-9\.]/', '', trim($_GET['version']));

  /**
   * Check is all the params filled with text
   *   and check if the version is in the right format.
   */
  if (!empty($name) &&
      !empty($type) &&
      !empty($version) &&
      preg_match('/^[0-9](\.[0-9])+$', $version)) {
    /**
     * Get the file path, here we use 'dirname' to get the absolute path
     *   if the download.php is on root
     */
    $filePath = dirname(__FILE__) . '/dl/' . $name . '/' . $version . '.' . $type;

    // Check if the file exist.
    if (file_exists($filePath)) {
      // Add headers
      header('Cache-Control: public');
      header('Content-Description: File Transfer');
      header('Content-Disposition: attachment; filename=' . $name . '.' . $type);
      header('Content-Length: ' . filesize($filePath));
      // Read file
      readfile($filePath);
    } else {
      die('File does not exist');
    }
  } else {
    die('Missing params');
  }
}
0 голосов
/ 19 января 2012

Возможно, вы просто захотите использовать заголовок размещения содержимого:

header('Content-disposition: attachment; filename=Project1.txt');
readfile('Project1/1.0.txt');
...