php中依赖注入深入理解

 更新时间:2016年11月25日 15:21  点击:1733
依赖注入是对于要求更易维护,更易测试,更加模块化的代码的答案。每个项目都有依赖(外界提供的输入), 项目越复杂,越需要更多的依赖。

PHP程序员如何理解依赖注入容器(dependency injection container)


背景知识

传统的思路是应用程序用到一个Foo类,就会创建Foo类并调用Foo类的方法,假如这个方法内需要一个Bar类,就会创建Bar类并调用Bar类的方法,而这个方法内需要一个Bim类,就会创建Bim类,接着做些其它工作。

<?php
// 代码【1】
class Bim
{
    public function doSomething()
    {
        echo __METHOD__, '|';
    }
}

class Bar
{
    public function doSomething()
    {
        $bim = new Bim();
        $bim->doSomething();
        echo __METHOD__, '|';
    }
}

class Foo
{
    public function doSomething()
    {
        $bar = new Bar();
        $bar->doSomething();
        echo __METHOD__;
    }
}

$foo = new Foo();
$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

使用依赖注入的思路是应用程序用到Foo类,Foo类需要Bar类,Bar类需要Bim类,那么先创建Bim类,再创建Bar类并把Bim注入,再创建Foo类,并把Bar类注入,再调用Foo方法,Foo调用Bar方法,接着做些其它工作。

<?php
// 代码【2】
class Bim
{
    public function doSomething()
    {
        echo __METHOD__, '|';
    }
}

class Bar
{
    private $bim;

    public function __construct(Bim $bim)
    {
        $this->bim = $bim;
    }

    public function doSomething()
    {
        $this->bim->doSomething();
        echo __METHOD__, '|';
    }
}

class Foo
{
    private $bar;

    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }

    public function doSomething()
    {
        $this->bar->doSomething();
        echo __METHOD__;
    }
}

$foo = new Foo(new Bar(new Bim()));
$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

这就是控制反转模式。依赖关系的控制反转到调用链的起点。这样你可以完全控制依赖关系,通过调整不同的注入对象,来控制程序的行为。例如Foo类用到了memcache,可以在不修改Foo类代码的情况下,改用redis。

使用依赖注入容器后的思路是应用程序需要到Foo类,就从容器内取得Foo类,容器创建Bim类,再创建Bar类并把Bim注入,再创建Foo类,并把Bar注入,应用程序调用Foo方法,Foo调用Bar方法,接着做些其它工作.

总之容器负责实例化,注入依赖,处理依赖关系等工作。


代码演示 依赖注入容器 (dependency injection container)

通过一个最简单的容器类来解释一下,这段代码来自 Twittee

<?php

class Container
{
    private $s = array();

    function __set($k, $c)
    {
        $this->s[$k] = $c;
    }

    function __get($k)
    {
        return $this->s[$k]($this);
    }
}

这段代码使用了魔术方法,在给不可访问属性赋值时,__set() 会被调用。读取不可访问属性的值时,__get() 会被调用。

<?php

$c = new Container();

$c->bim = function () {
    return new Bim();
};
$c->bar = function ($c) {
    return new Bar($c->bim);
};
$c->foo = function ($c) {
    return new Foo($c->bar);
};

// 从容器中取得Foo
$foo = $c->foo;
$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

这段代码使用了匿名函数

再来一段简单的代码演示一下,容器代码来自simple di container

<?php

class IoC
{
    protected static $registry = [];

    public static function bind($name, Callable $resolver)
    {
        static::$registry[$name] = $resolver;
    }

    public static function make($name)
    {
        if (isset(static::$registry[$name])) {
            $resolver = static::$registry[$name];
            return $resolver();
        }
        throw new Exception('Alias does not exist in the IoC registry.');
    }
}

IoC::bind('bim', function () {
    return new Bim();
});
IoC::bind('bar', function () {
    return new Bar(IoC::make('bim'));
});
IoC::bind('foo', function () {
    return new Foo(IoC::make('bar'));
});


// 从容器中取得Foo
$foo = IoC::make('foo');
$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

这段代码使用了后期静态绑定


依赖注入容器 (dependency injection container) 高级功能

真实的dependency injection container会提供更多的特性,如

    自动绑定(Autowiring)或 自动解析(Automatic Resolution)
    注释解析器(Annotations)
    延迟注入(Lazy injection)

下面的代码在Twittee的基础上,实现了Autowiring。

<?php

class Bim
{
    public function doSomething()
    {
        echo __METHOD__, '|';
    }
}

class Bar
{
    private $bim;

    public function __construct(Bim $bim)
    {
        $this->bim = $bim;
    }

    public function doSomething()
    {
        $this->bim->doSomething();
        echo __METHOD__, '|';
    }
}

class Foo
{
    private $bar;

    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }

    public function doSomething()
    {
        $this->bar->doSomething();
        echo __METHOD__;
    }
}

class Container
{
    private $s = array();

    public function __set($k, $c)
    {
        $this->s[$k] = $c;
    }

    public function __get($k)
    {
        // return $this->s[$k]($this);
        return $this->build($this->s[$k]);
    }

    /**
     * 自动绑定(Autowiring)自动解析(Automatic Resolution)
     *
     * @param string $className
     * @return object
     * @throws Exception
     */
    public function build($className)
    {
        // 如果是匿名函数(Anonymous functions),也叫闭包函数(closures)
        if ($className instanceof Closure) {
            // 执行闭包函数,并将结果
            return $className($this);
        }

        /** @var ReflectionClass $reflector */
        $reflector = new ReflectionClass($className);

        // 检查类是否可实例化, 排除抽象类abstract和对象接口interface
        if (!$reflector->isInstantiable()) {
            throw new Exception("Can't instantiate this.");
        }

        /** @var ReflectionMethod $constructor 获取类的构造函数 */
        $constructor = $reflector->getConstructor();

        // 若无构造函数,直接实例化并返回
        if (is_null($constructor)) {
            return new $className;
        }

        // 取构造函数参数,通过 ReflectionParameter 数组返回参数列表
        $parameters = $constructor->getParameters();

        // 递归解析构造函数的参数
        $dependencies = $this->getDependencies($parameters);

        // 创建一个类的新实例,给出的参数将传递到类的构造函数。
        return $reflector->newInstanceArgs($dependencies);
    }

    /**
     * @param array $parameters
     * @return array
     * @throws Exception
     */
    public function getDependencies($parameters)
    {
        $dependencies = [];

        /** @var ReflectionParameter $parameter */
        foreach ($parameters as $parameter) {
            /** @var ReflectionClass $dependency */
            $dependency = $parameter->getClass();

            if (is_null($dependency)) {
                // 是变量,有默认值则设置默认值
                $dependencies[] = $this->resolveNonClass($parameter);
            } else {
                // 是一个类,递归解析
                $dependencies[] = $this->build($dependency->name);
            }
        }

        return $dependencies;
    }

    /**
     * @param ReflectionParameter $parameter
     * @return mixed
     * @throws Exception
     */
    public function resolveNonClass($parameter)
    {
        // 有默认值则返回默认值
        if ($parameter->isDefaultValueAvailable()) {
            return $parameter->getDefaultValue();
        }

        throw new Exception('I have no idea what to do here.');
    }
}

// ----
$c = new Container();
$c->bar = 'Bar';
$c->foo = function ($c) {
    return new Foo($c->bar);
};
// 从容器中取得Foo
$foo = $c->foo;
$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

// ----
$di = new Container();

$di->foo = 'Foo';

/** @var Foo $foo */
$foo = $di->foo;

var_dump($foo);
/*
Foo#10 (1) {
  private $bar =>
  class Bar#14 (1) {
    private $bim =>
    class Bim#16 (0) {
    }
  }
}
*/

$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething

以上代码的原理参考PHP官方文档:反射,PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。

PHP调用系统的命令不管在linux还是在windows中只要权限足够都是可以执行了,下面我们就来看一个在linux中PHP调用linux外部命令的例子。


相信大家或多或少都用过AMH,Vestacp等vps面板,这些面板都是使用的php语言,从本质上来说就是php执行linux的外部命令。

PHP 为执行外部命令提供大量函数,其中包括 shell_exec()、exec()、passthru() 和 system()。这些命令是相似的,但为您运行的外部程序提供不同的界面。所有这些命令都衍生一个子进程,用于运行您指定的命令或脚本,并且每个子进程会在命令输出写到标准输出 (stdout) 时捕捉它们。

shell_exec函数

说明:通过 shell 运行外部程序,然后以字符串的形式返回结果。

语法:string shell_exec ( string $cmd )

返回值: 字符串

详细介绍
shell_exec() 命令行实际上仅是反撇号 (`) 操作符的变体,通过该命令可以运行shell命令,然后以字符串的形式返回结果。

示例代码

统计当前目录下所有文件中的单词数量,并输出前五行。


<?php
$results = shell_exec('wc -w *.txt | head -5');
echo "<pre>".$results . "
“;
?>

exec函数

说明:与 shell_exec() 相似,返回输出的最后一行

语法:string exec ( string $command [, array &$output [, int &$return_var ]] )
返回值: 字符串

详细介绍:
本函数执行输入 command 的外部程序或外部指令。它的返回字符串只是外部程序执行后返回的最后一行;若是 return_var 跟 output 二个参数都存在,则执行 command 之后的状态会填入 return_var 中。

实例代码:

统计当前目录下所有文件中的单词数量,并输出前五行,但是实际上只输出了一行。


<?php
$results = exec('wc -w *.txt | head -5');
echo $results;
 
#只会输出一行:
#3847 myfile.txt
?>
passthru()

说明:passthru() 允许您运行外部程序,并在屏幕上显示结果。

语法:void passthru ( string $command [, int &$return_var ] )
返回值: 整数

详细介绍:
passthru() 允许您运行外部程序,并在屏幕上显示结果。您不需要使用 echo 或 return 来查看结果;它们会显示在浏览器上。您可以添加可选的参数,即保存从外部程序返回的代码的变量,比如表示成功的 0,这为调试提供更好的机制。

实例代码:


<?php
passthru('wc -w *.txt | head -5',$returnval);
echo "<hr/>".$returnval;
?>
system函数

说明:执行外部程序并显示输出资料。

语法:string system ( string $command [, int &$return_var ] )
返回值: 字符串

详细介绍
system() 命令是一种混合体。它像 passthru() 一样直接输出从外部程序接收到的任何东西。它还像 exec() 一样返回最后一行,并使返回代码可用。

示例代码

<?php
system('wc -w *.txt | head -5');
 
#输出如下:
#123 file1.txt 332 file2.txt 444 file3.txt
#and so on
?>
小结

一般来说,exec() 命令比较常用;
如果不关心结果,并且命令比较简单时,可以使用 shell_exec();
如果仅需返回一个 shell 脚本,可以使用 passthru()。

不过小编还是要说一句,没有必须使用php执行系统函数了,我们可以禁止掉了,在php.ini中我们如下写

disable_functions = proc_open,exec,passthru,shell_exec,system,popen

就可以了。

php加密,php类,php分享

php 代码加密类,大家可以根据自己的需求进行修改,原类如下,希望能分享给大家。本次在ubuntu下测试没有问题。

    <?php  
    class Encryption{  
        private $c='';//存储密文  
        private $s='',$q1,$q2,$q3,$q4,$q5,$q6;//存储生成的加密后的文件内容  
        //如果不设置一个值,isset会表示不存在;  
        private $file='';//读取文件的路径  
        private $source='',$target='';
        //构造函数,实例化时调用初始化全局变量;  
        public function __construct(){  
            //初始化全局变量  
            $this->initialVar();  
            //echo "hello \n";  
        }  
        /*
        *@input  $property_name,$value
        *@output  
        *   魔法方法,对变量进行设置值;可根据需求进行处理。若直接去除if判断表示可用设置任何属性的值,包括不存在的属性;
        */  
        public function __set($property_name,$value){  
            //定义过的变量;  
            if(isset($this->$property_name)){  
                $this->$property_name = $value;  
            }else{  
                //异常处理,处理未声明的变量赋值;可根据需求进行处理。  
                throw new Exception("property does not exist");  
            }  
        }  
        //魔法方法 取出变量的值;  
        public function __get($property_name){  
            if(isset($this->$property_name)){  
                return $this->$property_name;  
            }else{  
                //throw new Exception("property does not exist");  
                return NULL;  
            }  
        }  
        //取随机排序  
        private function RandAbc($length=""){//随机排序取回  
          $str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  
          return str_shuffle($str);  
        }  
        //对明文内容进行加密处理
        private function ciphertext($filename){  
            //$filename='index.php';  
            $T_k1=$this->RandAbc();  
            $T_k2=$this->RandAbc();  
            $vstr=file_get_contents($filename);  
            $v1=base64_encode($vstr);  
            $c=strtr($v1,$T_k1,$T_k2);
            $this->c=$T_k1.$T_k2.$c;  
            return $this;  
        }
        //初始化变量  
        private function initialVar(){  
            $this->q1="O00O0O";//base64_decode  
            $this->q2="O0O000";//$c(原文经过strtr置换后的密文,由 目标字符+替换字符+base64_encode(‘原文内容’)构成)  
            $this->q3="O0OO00";//strtr  
            $this->q4="OO0O00";//substr  
            $this->q5="OO0000";//52  
            $this->q6="O00OO0";//urldecode解析过的字符串(n1zb/ma5\vt0i28-pxuqy*6%6Crkdg9_ehcswo4+f37j)

        }  
        //生成加密后的模板(复杂版本);  
        private function model(){  
            //$c = $this->c;
            //$this->initialVar();  
            $this->s='<?php $'.$this->q6.'=urldecode("%6E1%7A%62%2F%6D%615%5C%76%740%6928%2D%70%78%75%71%79%2A6%6C%72%6B%64%679%5F%65%68%63%73%77%6F4%2B%6637%6A");$'.  
            $this->q1.'=$'.$this->q6.'{3}.$'.$this->q6.'{6}.$'.$this->q6.'{33}.$'.$this->q6.'{30};$'.$this->q3.'=$'.$this->q6.'{33}.$'.$this->q6.'{10}.$'  
            .$this->q6.'{24}.$'.$this->q6.'{10}.$'.$this->q6.'{24};$'.$this->q4.'=$'.$this->q3.'{0}.$'.$this->q6.'{18}.$'.$this->q6.'{3}.$'.$this->q3.'{0}  
            .$'.$this->q3.'{1}.$'.$this->q6.'{24};$'.$this->q5.'=$'.$this->q6.'{7}.$'.$this->q6.'{13};$'.$this->q1.'.=$'.$this->q6.'{22}.$'.$this->q6.'{36}  
            .$'.$this->q6.'{29}.$'.$this->q6.'{26}.$'.$this->q6.'{30}.$'.$this->q6.'{32}.$'.$this->q6.'{35}.$'.$this->q6.'{26}.$'.$this->q6.'{30};  
            eval($'.$this->q1.'("'.base64_encode('$'.$this->q2.'="'.$this->c.'";
            eval(\'?>\'.$'.$this->q1.'($'.$this->q3.'($'.$this->q4.'($'.$this->q2.',$'.$this->q5.'*2),$'.$this->q4.'($'.$this->q2.',$'.$this->q5.',$'.$this->q5.'),  
            $'.$this->q4.'($'.$this->q2.',0,$'.$this->q5.'))));').'"));?>';  
            return $this;  
        }
        //创建加密文件  
        private function build($target){
            //$this->encodes("./index.php");  
            //$this->model();  
            $fpp1 = fopen($target,'w');  
            fwrite($fpp1,$this->s) or die('写入是失败!');
            fclose($fpp1);
            return $this;  
        }  
        //加密处理 连贯操作  
        public function encode($file,$target){  
            //$file = "index.php";  
            //连贯操作其实就是利用函数处理完后返回自身  
            $this->ciphertext($file)->model()->build($target);
            echo 'encode------'.$target.'-----ok<br/>';  
        }  
        //解密  
        public function decode($file,$target=''){
            //读取要解密的文件
            $fpp1 = file_get_contents($file);
            $this->decodeMode($fpp1)->build($target);
            echo 'decode------'.$target.'-----ok<br/>';
        }
        //解密模板,得到解密后的文本
        private function decodeMode($fpp1){
            //以eval为标志 截取为数组,前半部分为密文中的替换掉的函数名,后半部分为密文
            $m = explode('eval',$fpp1);
            //对系统函数的替换部分进行执行,得到系统变量
            $varStr = substr($m[0],strpos($m[0],'$'));
            //执行后,后续就可以使用替换后的系统函数名
            eval($varStr);
            //判断是否有密文
            if(!isset($m[1])){
                return $this;
            }

            //对密文进行截取 {$this->q4}  substr
            $star =  strripos($m[1],'(');
            $end = strpos($m[1],')');
            $str = ${$this->q4}($m[1],$star,$end);
            //对密文解密 {$this->q1}  base64_decode
            $str = ${$this->q1}($str);
            //截取出解密后的  核心密文
            $evallen = strpos($str,'eval');
            $str = substr($str,0,$evallen);
            //执行核心密文 使系统变量被赋予值 $O0O000
            eval($str);
            //并不能将如下段封装,因为 ${$this->qn} 并不能在全文中起作用
            $this->s = ${$this->q1}(
                ${$this->q3}(
                    ${$this->q4}(
                        ${$this->q2},${$this->q5}*2
                    ),
                    ${$this->q4}(
                        ${$this->q2},${$this->q5},${$this->q5}
                    ),
                    ${$this->q4}(
                        ${$this->q2},0,${$this->q5}
                    )
                )
            );
            return $this;
        }
        //递归读取并创建目标目录结构
        private function targetDir($target){
            if(!empty($target) )  {
                if(!file_exists($target)){
                    mkdir($target,0777,true);
                }else{
                    chmod($target,0777);
                }

            }
        }

        //递归解密 对指定文件夹下的php文件解密  
        public function decodeDir($source,$target=""){
            if(is_dir($source)){
                $this->targetDir($target);
                $dir = opendir($source);  
                while(false!=$file=readdir($dir))  
                {  
                    //列出所有文件并去掉'.'和'..' 此处用的实例为thinkphp框架,所以默认排除里Thinkphp目录,用户可以按照自己的需求设置
                    if($file!='.' && $file!='..' && $file !='ThinkPHP')
                    {  
                        $path = $target.DIRECTORY_SEPARATOR.$file;  
                        $sourcePath =  $source.DIRECTORY_SEPARATOR.$file;  
                        $this->decodeDir($sourcePath,$path);  
                    }  
                }  
          
            }else if(is_file($source)){  
                $extension=substr($source,strrpos($source,'.')+1);  
                if(strtolower($extension)=='php'){
                    $this->decode($source,$target);  
                }else{  
                    //不是php的文件不处理  
                    copy($source, $target);  
                }  
                //return;  
            }
        }  
        //递归加密 对指定文件夹下的php文件加密  
        public function encodeDir($source,$target){
            if(is_dir($source)){
                $this->targetDir($target);
                $dir = opendir($source);  
                while(false!=$file=readdir($dir))  
                {  
                    //列出所有文件并去掉'.'和'..'
                    if($file!='.' && $file!='..' && $file !='ThinkPHP')
                    {  
                        $path = $target.DIRECTORY_SEPARATOR.$file;  
                        $sourcePath =  $source.DIRECTORY_SEPARATOR.$file;  
                        $this->encodeDir($sourcePath,$path);  
                    }  
                }  

            }else if(is_file($source)){
                $extension=substr($source,strrpos($source,'.')+1);
                if(strtolower($extension)=='php'){
                    $this->encode($source,$target);
                }else{  
                    copy($source, $target);  
                }
            }  
        }
    }  
    $ob = new Encryption();  
    $ob->source = "/var/www/bookReservation";
    $ob->target = "/var/www/jiami/bookReservation";
    //解密指定文件  
    //$ob->decode('D:\\php\\WWW\\workspace\\weixin2\\Application\\Home\\Controller\\IndexController.class.php');  
      
    //$ob->decode('jiami.php');  
    //$ob->decode('dam6.php');  
    //对一个指定的文件目录进行加密  
    $ob->encodeDir($ob->source,$ob->target);
    //对一个指定的文件目录进行解密
    $ob->decodeDir($ob->target,"/var/www/jiami/bookReservationD");

exec()、passthru()、system()、shell_exec()在php配置文件中通常是把它给禁止使用了,但有时我们需要用到了,下面就来看看php中exec()、passthru()、system()、shell_exec()函数的用法与禁止方法。

php提供4种方法执行系统外部命令:exec()、passthru()、system()、 shell_exec()。
在开始介绍前,先检查下php配置文件php.ini中是有禁止这是个函数。找到 disable_functions,配置如下:
disable_functions =
如果“disable_functions=”后面有接上面四个函数,将其删除。
默认php.ini配置文件中是不禁止你调用执行外部命令的函数的。

方法一:exec()

function exec(string $command,array[optional] $output,int[optional] $return_value)
php代码:


<?php
        echo exec("ls",$file);
        echo "</br>";
        print_r($file);
?>
执行结果:
test.php
Array( [0] => index.php [1] => test.php)

知识点:

exec 执行系统外部命令时不会输出结果,而是返回结果的最后一行,如果你想得到结果你可以使用第二个参数,让其输出到指定的数组,此数组一个记录代表输出的一行,即如果输出结果有20行,则这个数组就有20条记录,所以如果你需要反复输出调用不同系统外部命令的结果,你最好在输出每一条系统外部命令结果时清空这个数组,以防混乱。第三个参数用来取得命令执行的状态码,通常执行成功都是返回0。

方法二:passthru()

function passthru(string $command,int[optional] $return_value)
代码:


<?php
        passthru("ls");
?>
执行结果:
index.phptest.php
知识点:
passthru与system的区别,passthru直接将结果输出到浏览器,不需要使用 echo 或 return 来查看结果,不返回任何值,且其可以输出二进制,比如图像数据。

方法三:system()

function system(string $command,int[optional] $return_value)
代码:


<?php
        system("ls /");
?>
执行结果:
binbootcgroupdevetchomeliblost+foundmediamntoptprocrootsbinselinuxsrvsystmpusrvar
知识点:
system和exec的区别在于system在执行系统外部命令时,直接将结果输出到浏览器,不需要使用 echo 或 return 来查看结果,如果执行命令成功则返回true,否则返回false。第二个参数与exec第三个参数含义一样。


方法四:反撇号`和shell_exec()

shell_exec() 函数实际上仅是反撇号 (`) 操作符的变体

代码:


<?php
        echo `pwd`;
?>


执行结果:


/var/www/html

CMS为了文章编辑内容,都会在后台集成在线编辑器,如FCKEditor等,但是这种很容易XSS跨站攻击,以下我们来看一下使用 HTML Purifier 如何防止xss跨站攻击

随着html可视即可得编辑器的流行,很多网站使用了这样的编辑器,比如FCKEditor、百度UEditor编辑器等等。

跨站脚本攻击(XSS)已经不是什么新鲜的话题了,甚至很多大公司也为此吃尽苦头。最简单直接的防范方法,就是不允许任何html标签输入,对用户输入进行编码(htmlencode)。

但是如果想用户输入支持一些格式,怎么办?一种办法就是很多论坛采用的BB Code的方法。使用特定的标签代替一些格式。比如:[ B ]表示粗体,等等。但是,BB Code这种形式并不被广泛接受,它的表现力实在太差了,而且并不是标准格式。

为了让用户的输入更具表现力,涌现了大量的Html编辑器控件,著名的有FCKEditor,FreeTextBox,Rich TextBox,Cute Editor,TinyMCE等等。我个人比较喜欢Cute Editor,功能强大,性能不错,而且容易定制。

使用这些Html编辑器控件的潜在危险,是用户可能会输入一些危险字符,注入到网站中,形成XSS攻击。一个最简单的输入就是:

<script>alert('xss')</script>

XSS 输入攻击也可能是 HTML 代码段,譬如:

(1).网页不停地刷新 <meta http-equiv="refresh" content="0;">
(2).嵌入其它网站的链接 <iframe src=http://xxxx width=250 height=250></iframe>

对于PHP开发者来说,如何去防范XSS攻击呢?(php防止xss攻击的函数),这里飘易推荐HTML Purifier工具。

HTML Purifier官网:http://htmlpurifier.org/

HTML Purifier是基于php 5所编写的HTML过滤器,支持自定义过滤规则,还可以把不标准的HTML转换为标准的HTML,是WYSIWYG编辑器的福音。
HTML Purifier,这是一个符合W3C标准的HTML过滤器,可以生成标准的HTML代码,并且有很多的自定义配置,可以过滤掉javascript代码等,有效的防止XSS!

一、使用HTML Purifier的要求

HTML Purifier 只需要PHP 5.0.5以及以上版本,并且不需要其他核心组件的支持。HTML Purifier 不兼容  zend.ze1_compatibility_mode。

以下5个是可选扩展,可以增强HTML Purifier的性能(can enhance the capabilities of HTML Purifier):

    * iconv  : Converts text to and from non-UTF-8 encodings
    * bcmath : Used for unit conversion and imagecrash protection
    * tidy   : Used for pretty-printing HTML
    * CSSTidy : Clean CSS stylesheets using %Core.ExtractStyleBlocks
    * Net_IDNA2 (PEAR) : IRI support using %Core.EnableIDNA

使用前请阅读HTML Purifier详细安装说明:http://htmlpurifier.org/live/INSTALL

二、基本用法

默认下,使用UTF-8编码,和XHTML 1.0 Transitional文档类型.
require_once('HTMLPurifier/library/HTMLPurifier.auto.php');
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
 
$dirty_html = <<<EOF 
<h1>Hello 
<script>alert("world");</script> 
EOF; 

$cleanHtml = $purifier->purify($dirty_html); 

输出:

<h1>Hello 
</h1> 

过滤了XSS代码,过滤规则:http://htmlpurifier.org/live/smoketests/xssAttacks.php

自动填充了残缺的标签

三、使用配置

配置主要用于设置规则,使用比较简单

$config = HTMLPurifier_Config::createDefault(); 
// something.... 
$purifier = new HTMLPurifier($config); 

详细的配置规则:http://htmlpurifier.org/live/configdoc/plain.html

[!--infotagslink--]

相关文章

  • phpems SQL注入(cookies)分析研究

    PHPEMS(PHP Exam Management System)在线模拟考试系统基于PHP+Mysql开发,主要用于搭建模拟考试平台,支持多种题型和展现方式,是国内首款支持题冒题和自动评分与教师评分相...2016-11-25
  • ASP/PHP sql注入语句整理大全

    SQL注入攻击指的是通过构建特殊的输入作为参数传入Web应用程序,而这些输入大都是SQL语法里的一些组合,通过执行SQL语句进而执行攻击者所要的操作 标准注入语句1.判...2016-11-25
  • PHP防止SQL注入的例子

    防止SQL注入是我们程序开发人员必须要做的事情了,今天我们就来看一篇关于PHP防止SQL注入的例子了,具体的实现防过滤语句可以参考下面来看看吧。 使用prepared以及参...2016-11-25
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • php中去除文字内容中所有html代码

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • index.php怎么打开?如何打开index.php?

    index.php怎么打开?初学者可能不知道如何打开index.php,不会的同学可以参考一下本篇教程 打开编辑:右键->打开方式->经文本方式打开打开运行:首先你要有个支持运行PH...2017-07-06
  • PHP中func_get_args(),func_get_arg(),func_num_args()的区别

    复制代码 代码如下:<?php function jb51(){ print_r(func_get_args()); echo "<br>"; echo func_get_arg(1); echo "<br>"; echo func_num_args(); } jb51("www","j...2013-10-04
  • PHP编程 SSO详细介绍及简单实例

    这篇文章主要介绍了PHP编程 SSO详细介绍及简单实例的相关资料,这里介绍了三种模式跨子域单点登陆、完全跨单点域登陆、站群共享身份认证,需要的朋友可以参考下...2017-01-25
  • AngularJS 依赖注入详解及示例代码

    本文主要介绍AngularJS 依赖注入的知识,这里整理了相关的基础知识,并附示例代码和实现效果图,有兴趣的小伙伴可以参考下...2016-08-24
  • PHP实现创建以太坊钱包转账等功能

    这篇文章主要介绍了PHP实现创建以太坊钱包转账等功能,对以太坊感兴趣的同学,可以参考下...2021-04-20
  • PHP中自带函数过滤sql注入代码分析

    SQL注入攻击是黑客攻击网站最常用的手段。如果你的站点没有使用严格的用户输入检验,那么常容易遭到SQL注入攻击。SQL注入攻击通常通过给站点数据库提交不良的数据或...2016-11-25
  • php微信公众账号开发之五个坑(二)

    这篇文章主要为大家详细介绍了php微信公众账号开发之五个坑,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-10-02
  • ThinkPHP使用心得分享-ThinkPHP + Ajax 实现2级联动下拉菜单

    首先是数据库的设计。分类表叫cate.我做的是分类数据的二级联动,数据需要的字段有:id,name(中文名),pid(父id). 父id的设置: 若数据没有上一级,则父id为0,若有上级,则父id为上一级的id。数据库有内容后,就可以开始写代码,进...2014-05-31
  • PHP如何通过date() 函数格式化显示时间

    这篇文章主要介绍了PHP如何通过date() 函数格式化显示时间,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-11-13
  • PHP+jQuery+Ajax实现多图片上传效果

    今天我给大家分享的是在不刷新页面的前提下,使用PHP+jQuery+Ajax实现多图片上传的效果。用户只需要点击选择要上传的图片,然后图片自动上传到服务器上并展示在页面上。...2015-03-15
  • golang与php实现计算两个经纬度之间距离的方法

    这篇文章主要介绍了golang与php实现计算两个经纬度之间距离的方法,结合实例形式对比分析了Go语言与php进行经纬度计算的相关数学运算技巧,需要的朋友可以参考下...2016-07-29
  • PHP如何使用cURL实现Get和Post请求

    这篇文章主要介绍了PHP如何使用cURL实现Get和Post请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-11
  • 谈谈PHP中相对路径的问题与绝对路径的使用

    经常看到有人踩在了PHP路径的坑上面了,感觉有必要来说说PHP中相对路径的一些坑,以及PHP中绝对路径的使用,下面一起来看看。 ...2016-08-24
  • thinkPHP中多维数组的遍历方法

    这篇文章主要介绍了thinkPHP中多维数组的遍历方法,以简单实例形式分析了thinkPHP中foreach语句的使用技巧,需要的朋友可以参考下...2016-01-12
  • PHP正则表达式过滤html标签属性(DEMO)

    这篇文章主要介绍了PHP正则表达式过滤html标签属性的相关内容,实用性非常,感兴趣的朋友参考下吧...2016-05-06