Search code examples
phpurlurl-rewritingurlencodescandir

PHP: safely transform a file name into an URL


I wrote a PHP script who scans a directory for pdf files and then create an HTML page with the list of this files and their relative link. The name of the file will be used for the list items.

How can i ensure a good compatibility between special chars and the URL?

For example, i have a file that contains text 49% text.pdf and the server is responding to the URL http://localhost/folder/text%2049%%20text.pdf with a Bad Request error.

I tried using the urlencode() with no success. How can i improve my script?

UPDATE

urlencode() returns me <a href="text+49%25+text.pdf">text 49% text.pdf</a>, and with this i get the Bad Request error.


Solution

  • You have to use rawurlencode(). That will convert both % to %25 and spaces to %20