Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL/HTML Escaping/Encoding

I have always been confused with URL/HTML Encoding/Escaping. I am using PHP, so want to clear somethings up.

Can I say that I should always use

  • urlencode: for individual query string parts

    $url = 'http://test.com?param1=' . urlencode('some data') . '&param2=' . urlencode('something else');
    
  • htmlentities: for escaping special characters like <> so that if will be rendered properly by the browser

Would there be any other places I might use each function. I am not good at all these escaping stuff, always confused by them

like image 951
Jiew Meng Avatar asked Jan 24 '11 14:01

Jiew Meng


People also ask

How do you escape an HTML URL?

The link would then be technically broken. Regardless, you basically just need to replace the percents % by their URL-encoded representation %25 (in other words: just encode the URL twice).

What does %20 replace in URL?

URL Encoding (Percent Encoding) URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is %2f in a URL?

URL encoding converts characters into a format that can be transmitted over the Internet. - w3Schools. So, "/" is actually a seperator, but "%2f" becomes an ordinary character that simply represents "/" character in element of your url. Follow this answer to receive notifications.


1 Answers

First off, you shouldn't be using htmlentites around 99% of the time. Instead, you should use htmlspecialchars() for escaping text for use inside xml/html documents. htmlentities are only useful for displaying characters that the native characterset you're using can't display (it is useful if your pages are in ASCII, but you have some UTF-8 characters you would like to display). Instead, just make the whole page UTF-8 (it's not hard), and be done with it.

As far as urlencode, you hit the nail on the head.

So, to recap:

  • Inside HTML:

    <b><?php echo htmlspecialchars($string, ENT_QUOTES, "UTF-8"); ?></b>
    
  • Inside of a url:

    $url = '?foo='.urlencode('bar');
    
like image 191
ircmaxell Avatar answered Oct 21 '22 02:10

ircmaxell