I'm making links through a php script to files which sometimes have spaces in them. So I'm replacing all instances of a space with %20 and then echoing the html for the link.
But I'm having a problem where it seems to just ignore %20 and add a space instead. If I manually type the URL with %20 for the spaces the file does get found. I've tried using "+" which does show up in the URL, but the url doesn't work and the file is not found.
<?php $newfilename = str_replace(" ", "%20", $docs['filename']) ?>
<a href=http://<?php echo $_SERVER['HTTP_HOST']."/database/
candidates/".$newfilename;?>><"Filename"></a>
So if the filename is "test file.doc" then the url is "mysite.com/database/candidates/test file.doc"... it ignores the %20.
How can I make this work with files with spaces in the name?
You should use the built in function rawurlencode (or the closely related urlencode)
$newfilename = rawurlencode($docs['filename']);
urlencode
is used for encoding querystring arguments, which will probably work here since all you have are spaces. However, rawurlencode
works with the path of a URL, which is what you're using in your example. (the examples given for both in the documentation back that up)
Have you tried rawurlencode()
?
<a href=http://<?php echo $_SERVER['HTTP_HOST']."/database/candidates/".rawurlencode($newfilename);?>>
<"Filename">
</a>
It is probably a better idea to put the whole URL in as the parameter though:
<?php $url = rawurlencode("http://{$_SERVER['HTTP_HOST']}/database/candidates/$newfilename"); ?>
<a href="<?php echo $url;?>">
<"Filename">
</a>