0

I am testing a small bit of code to download a file but nothing downloads. I have looked at countless examples (I know this has been asked many times) and from reading these examples this should work. The file definitely exists but no download.

What am I doing wrong?

This is the file (called download.php) in its entirety.

<?php

$file = $_SERVER["DOCUMENT_ROOT"] . "/uploads/test.png" ;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

It is called with a simple js function:

function download() {

    $.post("download.php", 
        function(data, status){
          ... some stuff will go in here
        }
    );
}
2
  • 2
    AJAX doesn't do downloads. The file contents are in data. Commented Sep 1, 2023 at 20:50
  • 1
    As @Barmar said, AJAX doesn't do downloads. A simple solution is use something like location.href='download.php' Your browser will trigger the download. Commented Sep 1, 2023 at 20:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.