Hot Dog Hot Dog - 4 months ago 25
Ajax Question

Check if (download)file exist with AJAX & PHP

I have a download-page where visitors can enter the name of a ZIP-file (without the extension) in an INPUT-field.

index.php :

<form action="download-script.php" method="post">
<input type="text" name="file" placeholder="Enter filename here" />
<input type="submit" value="Download starten" />
</form>


The ZIP-files are stored in a separate folder "files". If the visitor knows the name of the file everything is fine. If the file name is being misspelled or empty, an error message is displayed by the script:

download-script.php :

<?php

$file = preg_replace("/[^0-9a-z.\-_ ]/i", "", $_POST['file']);
$file = 'download/' . $file . '.zip';

if (file_exists($file)) {
header('Content-Disposition: attachement; filename=' . basename($file));
header('Content-Type: application/force-download');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . filesize($file));
header('Connection: close');
readfile($file);
}
else {
echo "File not found";
exit;
}
?>


My aim is to show the error-message on
index.php
and not on
download-script.php
because
download-script.php
will only show the error-message.

Answer

In index.php

<?php
if (isset($_REQUEST["error"])) {
    echo "File not found";
}
?>
<form action="download-script.php" method="post">
<input type="text" name="file" placeholder="Enter filename here" />
<input type="submit" value="Download starten" />
</form>

In download-script.php

<?php
$file = preg_replace("/[^0-9a-z.\-_ ]/i", "", $_POST['file']);
$file = 'download/' . $file . '.zip';

if (file_exists($file)) {
    header('Content-Disposition: attachement; filename=' . basename($file));
    header('Content-Type: application/force-download');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Content-Length: ' . filesize($file));
    header('Connection: close');
    readfile($file);
} 
else {
    header('Location: index.php?error=1');
    exit;
}
?>

You can try ajax but it's more complicated and harder to debug, see this or this question for an example.