mysql file download

Asked

Viewed 2,351 times

1

I have files in my database that I’d like to download. These files are of various extensions; . pdf, . txt, doc, . xlxs, etc;

I looked in many places but found nothing detailed (for beginners).

I want to make a list of the files you have in my bank and generate a download link.

  • 1

    What is the table like in the database? Does it contain a reference where the file is, or is the file literally inside the database? (example, is a path, guy C:\arquivos\teste.pdf?)

  • the file is inside the upload folder and the path in the database is uploads/filename.extensao

  • @Rafaelacioly, post the part that is in difficulty so that we can help you, show how the information is coming to the view.

  • @Rafaelacioly, it’s just you make a select * from table in mysql, then do a foreach in the data and an echo in the folder and name of the files. This is detailed on my website: http://www.tocadigital.com.br

  • Managed to solve the problem Rafael?

2 answers

1


Public directory

The briefcase ./upload being "publish" then we can access your files, the files being static just list the mysql data and create a .htacces in the briefcase ./upload to force the download of files in such a folder, for example:

CREATE TABLE IF NOT EXISTS `arquivos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `path` varchar(800) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

The SELECT would look something like:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
}

$query = 'SELECT path FROM `arquivos`';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        echo '<a href="', $row['path'],
             '">Download de ', basename($row['path']),
             '</a>';
    }

    $result->close();
}

$mysqli->close();

.htaccess should be in the same folder as the files:

<FilesMatch "\.(?i:mov|mp3|jpg|pdf)$"> #altere nesta linha os tipos de arquivos
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>

However if you don’t have access or use apache you can try the attribute download="", would look something like:

$query = 'SELECT path FROM `arquivos`';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $nome = basename($row['path']);

        echo '<a download="', $nome,'" href="', $row['path'],
             '">Download de ', $nome,
             '</a>';
    }

    $result->close();
}

$mysqli->close();

Private directory

If you do not want to allow direct access to the directory or have no access because it is not inside the server folder you may need to create a php or a route with . htaccess,

Assuming (hypothetical) the server files are in /etc/var/www (or in windows c:/www) and the files for download in /home/user/upload (or in windows c:/upload) then you should create a . php like this:

$query = 'SELECT path FROM `arquivos`';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $nome = basename($row['path']);

        echo '<a href="download.php?file=', urlencode($nome),
             '">Download de ', $nome,
             '</a>';
    }

    $result->close();
}

$mysqli->close();

and the download.php file should be something like:

Using excerpt from this answer /a/73497/3635

<?php
$nome = isset($_GET['file']) ? $_GET['file'] : null;
$fullPath = '/home/user/upload/' . $nome;

if ($nome === null) {
    echo 'Parametro file não definido';
    exit;
} else if (false === is_file($fullPath)) {
    echo 'Arquivo não encontrado';
    exit;
}

function mimeType($file) {
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

$mime = mimeType($fullPath);

if ($mime === false) {
    echo 'Não foi possível detectar o tipo de arquivo';
    exit;
}

header('Content-type: ' . $mime);

//Seta o tamanho do arquivo
header('Content-length: ' . filesize($fullPath));

//Força o download
header('Content-Disposition: attachment; filename=' . $nome);

//Este header é necessário
header('Content-Transfer-Encoding: binary');

echo file_get_contents($fullPath, FILE_BINARY);

0

Technically it’s simple, you just need to request on DB and do a while writing:

<a href="<? echo $row[link_conteudo']?>"><? echo $row[titulo']?></a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.