when constructing a url from user’s input, is it better to use urlencode() than htmlentities()? eg:
//$usr is from $_POST
$url = ‘www.site.come/index.php?usr=’ . urlencode($usr);
is better than
$url = ‘www.site.come/index.php?usr=’ . htmlentities($usr, ENT_QUOTES);
I was told that ‘For a doctype of XHTML, htmlentities will work (on most
browsers), but it’s invalid for HTML documents(either strict or transitional), urlencode() is the most reliable and cross-browser compatible solution’.
Is this true? I can’t find any resource on the web to back this point.
Thanks.
Urlencode() is used to encode strings for urls.
HTMLentities() is a way to encode a HTML string, so that when displayed in a file it’s not parsed by the browser.
Therefore, use urlencode().
Just to elaborate a bit on, what arkinstall already said;
You use urlencode to encode strings in URL’s. You use htmlspecialchars (or htmlentities) to encode strings in HTML.
Thus, if you create a URL, which has GET parameters, you should encode these with urlencode. And if this URL is placed in a HTML attribute (Such as the action attribute of a form element), you should further encode the URL with htmlspecialchars. Browsers are forgiving, so they will understand it even if you forget to HTML-encode the URL in an attribute. For the document to be valid XHTML, you have to do it though.
Hi, arkin & kyber
Thanks for the reply, that’s helpful.