PHP 执行系统命令可以使用以下几个函数:
system、exec、passthru、 ·· 反引号、shell_exec、popen、proc_open、pcntl_exec
stringsystem (string$command[,int&$return_var])
stringexec(string$command[,array&$output[,int&$return_var]])
voidpassthru(stringcommand,int&return_var)
stringshell_exec(stringcommand)
`` 反引号
resourcepopen(string$command,string $mode)
resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env[,array$other_options]]])
voidpcntl_exec(string$path[,array$args [,array$envs]])
下面就说说一下这些函数的用法:
system 他可以执行windows命令例如:whoami,ipconfig, dir 等命令
<?php
$id = $_GET['id'];
system($id);
?>
//在浏览器打开在url后面加?id=就可以输入命令了
exec 和system差不多;
<?php
$id = $_GET['id'];
echo exec($id);
?>
<?php
$id = $_GET['id'];
echo shell_exec($id);
?>
<?php
$id = $_GET['id'];
echo `$id`;
?>
<?php
$id = $_GET['id'];
passthru($id);
?>
<?php
$id = $_GET['id'];
echo popen($id,'r'); //popen,里面是需要参数的'r'表示读权限,'w'是写
?>
proc_popen我不怎么熟,它不适合windows下实验,有兴趣的可以百度一下啊!
pcntl_exec是Linux下的一个扩展,可以支持多线程操作,在这不怎么多讲
他们的用法都差不多,有的可以直接输出,有的需要输出命令才能输出,大家可以复制一下,来自己实验一下,自己体会他们的区别哈
用来防御的函数
escapeshellarg(string$arg)
可以用到 php 的安全中,会过滤掉 arg 中存在的一些特殊字符。在输入的参数中如果包含中 文传递给 escapeshellarg,会被过滤掉。
escapeshellcmd(string$command)
escapeshellcmd()函数会转义命令中的所有 shell 元字符来完成工作。这些元字符包括: #&;` , |*?~ <>^()[]{}$\\。
他们都差不多,主要是对一些字符进行转义,有些操作是可以做到的 但是他们具有符号的操作是进行不了的,例如:url?id=echo '132465' >> 1.txt 等这些命令是执行不了的,虽然可以绕过,但总比没有要好的多
<?php
$id = $_GET['id'];
system(escapeshellcmd($id));
?>