URL / HTML转义/编码 [英] URL/HTML Escaping/Encoding

查看:312
本文介绍了URL / HTML转义/编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直与URL / HTML编码/转义混淆。我正在使用PHP,所以想清除一些东西。

我可以说我应该总是使用


  • urlencode :用于单个查询字符串部分

      $ url ='http:// test.com?param1 ='。 urlencode('一些数据')。 '& param2 ='。 urlencode('别的东西'); 


  • htmlentities 字符如<> ,以便如果将被浏览器正确呈现




会有其他地方我可能会使用每个功能。我不善于处理所有这些逃脱的东西,总是被他们所困惑。

首先,你不应该使用<$大约99%的时间是c $ c> htmlentites 。相反,您应该使用 htmlspecialchars() htmlentities 仅用于显示您正在使用的本机字符集无法显示的字符(如果您的网页使用ASCII码,但有一些UTF-8你想要显示的字符)。相反,只是使整个页面UTF-8(这并不难),并完成它。



至于 urlencode

所以,回顾一下:





    $ b

     < b><?php echo htmlspecialchars($ string,ENT_QUOTES ,UTF-8); ?>< / B个


  • 网址内:

      $ url ='?foo ='。urlencode('bar'); 



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

解决方案

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');
    

这篇关于URL / HTML转义/编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆