Reputation: 21
I know this issue has already been addressed before but those programs had the header function whereas I am using a href to enable file download.
The issue is that whenever a file has %20 in it, it fails to download.
It gives a 404 error and the file
For example: no%love.mp3
gets replaces with no love.mp3
I tried uploading files with %20 in between the filename and when I click on the download link it opens up with a file not found error.
There is no issue when I upload files with space in them. They are getting downloaded as it is. The issue only arises with files with %20.
Code for download:
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) != false)
{
if ($filename != '.' && $filename != '..') //removing . and .. files
{
?>
<p><a href="<?php echo $dir . '/' . $filename; ?>" target="_blank"> //download link
<?php echo $filename;?></a></p> //displaying the file name
<?php
}
}
closedir($dir_list);
}
Please help me with this issue. I thought of using str_replace() but I am not sure where exactly should I use it.
Thanks in advance.
Upvotes: 1
Views: 1184
Reputation: 2350
I think @Suresh Koya was about right, except you need to encode it instead.
%20 is considered a space character in the context of a URL, as I'm sure you know.
If your file name contains %20, and you just print it directly like you did, the browser will interpret this to be a space, rather than the literal %20 it is.
For this reason, you need to urlencode() the file name before you print it. This way the %20 will be made to be read as exactly that, and won't swap it for a space.
So, your answer:
<p><a href="<?php echo $dir . '/' . urlencode($filename); ?>" target="_blank"> //download link
<?php echo $filename;?></a></p> //displaying the file name
Upvotes: 2
Reputation: 44831
Best solution: just don't have file names with actual %20
in them; fix that at upload time. Allowing them is going to give you headaches (and probably means you aren't properly validating file names in other ways, leaving you open to various hacks).
That said, if you must have names with literal %20
in them, then the URL needs to contain %2520
(an encoded %
and literal 20
). You'll want to use urlencode()
to handle all scenarios correctly when generating the URL.
Upvotes: 0