LazyNinja LazyNinja - 6 months ago 16x
PHP Question

File downloading giving error when file has %20. (PHP)

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


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.


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