Search code examples
phpcakephpcakephp-1.3urlencodeurl-encoding

How to safely pass parameters in the url


I am using urls like this parameters

http://localhost/articles/?author=Ben%20Cooper%2CAlex%20Hunter&title=.....&tags=..

I urlencode them in the links. This all works until there are special characters in the parameters.

For example

http://localhost/articles/?author=..&title=&tags=..

If, in title I have Love & Life, first time it encodes it has Love+%26+Life, sometimes it becomes Love+%26amp%3B+Life.

Why is this happening? I appreciate any help.


Solution

  • You need to use html_entity_decode() first. That will turn & (which is encoded for html, not urls) into & then unlencode() which will turn it into %26

    HTML and URLs have different reserved chars and are encoded differently. A lot of frameworks will automatically encode html entities to help prevent your page from rendering oddly. Imagine you had < in a string, that could screw up the page when it was displayed so it will get echo'd to the html as &lt; and the browser will render it as <instead of treating it as part of a tag.

    You can't directly encode &lt; into %3C (< urlencoded) because it will think you literally want to encode &lt; and not < this is why you need to make a pass through html_entity_decode()

    Here is a code snippet:

    $str = 'Love &amp; Life'; //start with string that may or may not contain htmlentities
    $decodedStr = html_entity_decode($str); //replace html entities with their literal counterparts
    $urlEncodedStr = urlencode($decodedStr); //urlencode!
    

    Hope this helps!