I created a download.php file in my vps server which has some images, if users request the file using this file, the file is saved to the devices. But this creates an empty file. This is the code.
<?php
if(isset($_GET['file']))
{
$filename = $_GET["file"];
if(preg_match('/^[^.][-a-z0-9_.] [a-z]$/i', $file)){
$filepath = "images/" . $file;
if(file_exists($filepath)) {
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$filename."\"");
readfile($filepath);
}
}
?>
I have corrected the typos and removed echo still , it is the same, The file is downloaded when download.php?file=abstract.jpg
is invoked on the server.
CodePudding user response:
There is still a couple of errors in your code:
There is no closing parentheses for your initial if block
Your preg_match - you're passing a variable $file to it which hasn't been declared. I think you mean to pass $filename. If I am not mistaken, your code is continuing because the preg_match isn't returning false.
You're passing $file to create the $filepath variable too, so again, it's just trying to download images/ instead of the full path.
This code works:
<?php
if(isset($_GET['file']))
{
$filename = $_GET["file"];
if(preg_match('/^[^.][-a-z0-9_.] [a-z]$/i', $filename)){
$filepath = "images/" . $filename;
if(file_exists($filepath)) {
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$filename."\"");
readfile($filepath);
}
}
}