Home >php教程 >PHP源码 >封装防sql注入的方法

封装防sql注入的方法

PHP中文网
PHP中文网Original
2016-05-23 16:33:561135browse

php代码

<?php


/**
 * 批量实体转义
 * @param $data
 * @return array|string
 */
function deepSpecialChars($data)
{
    if (empty($data)) {
        return $data;
    }

    return is_array($data) ? array_map("deepSpecialChars", $data) : htmlspecialchars($data);

}

/**
 *批量单引号转义
 * @param $data
 * @return array|string
 */
function deepSlashes($data)
{
    if (empty($data)) {
        return $data;
    }
    return is_array($data) ? array_map(&#39;deepSlashes&#39;, $data) : addslashes($data);
}


//调用案例
$arr = array(&#39;username&#39; => &#39;张三<p></p>&#39;, &#39;age&#39; => "18&#39;#", &#39;desc&#39; => &#39;<script>alert("hello")</script>&#39;);


$arr = deepSpecialChars($arr);//标签转义成实体
$arr = deepSlashes($arr);//单引号转义

print_r($arr);


//result
/*
Array
(
    [username] => 张三&lt;p&gt;&lt;/p&gt;
    [age] => 18\&#39;#
    [desc] => &lt;script&gt;alert(&quot;hello&quot;)&lt;/script&gt;
)
*/
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn