Search code examples
phpurlencodinghtml-entitieshtmlspecialchars

Using htmlspecialchars on a URL


I have URLs in this format :

http://site.com/index.php?title=[SOME_UNICODE_TITLE]&id=[ID]&type=[TYPE]

When I try to use htmlspecialchars on this URL to encode unicode title the function encodes & too; so it will be &amp so variable name id is converted to ampid ! So I can't read it from code.

How can I use htmlspecialchars on a URL without converting URL specific chars (e.g. &,=,...)?


Solution

  • IMHO you should just use urlencode() for URLs, because that's what it is made for. If you cannot / do not want to use it and you always get a full URI. You could parse if before encoding it:

    $uriParts = parse_url($fullUri);
    $queryParts = array();
    parse_str($uriParts['query'], $queryParts);
    
    foreach($queryParts as $name => $value) {
        $queryParts[$name] = htmlspecialchars($value);
    
        // don't know whether you want to encode the key too
    }
    

    http://php.net/manual/en/function.parse-str.php
    http://www.php.net/manual/en/function.parse-url.php

    Example: http://codepad.viper-7.com/lIFiHB