Anon
Anon

Reputation: 13

Create download link

file.php

<a href="download.php?filename=<?php echo $basename; ?>">&nbsp;&nbsp;<?php echo $filename; ?></a>

The $basename will return a value such as id_filename.extension which is the real name of the files inside the server

download.php

<?php
    require_once 'database.php';
    require_once 'session.php';
    require_once 'session-login.php';
    require_once 'session-timeout.php';
    require_once 'valid-user.php';

    $folder = $userid;
    $file_name = $_GET['filename'];
    $file = 'C:xampp/htdocs/project/user/'.$folder.'/'.$file_name;

    if (file_exists($file)) {
        header('Content-Type: ' . mime_content_type($file_name));
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
    } else {
        header('HTTP/1.1 404 Not Found');
    }
?>

It did download the files. But when i open the file, i get error below even if the files does exist in the server:

<b>Warning</b>:  mime_content_type(id_filename.extension): failed to open stream: No such file or directory in <b>C:\xampp\htdocs\project\download.php</b> on line <b>12</b><br />

Upvotes: 1

Views: 166

Answers (2)

Ivan
Ivan

Reputation: 11

I think you should type this:

Content-Type: application/octet-stream

instead of

Content-Type: mime_content_type($file_name)

Upvotes: 1

Oleg Dubas
Oleg Dubas

Reputation: 2348

You should get the mime type from $file (with entire path) not by just $filename:

$file = 'C:xampp/htdocs/project/user/'.$folder.'/'.$file_name;
if (file_exists($file)) {
    header('Content-Type: ' . mime_content_type($file));

Upvotes: 1

Related Questions