php $_GET $_POST过滤sql注入程序代码

 更新时间:2016年11月25日 15:09  点击:2023
本文章来给大家介绍一个php $_GET $_POST过滤sql注入程序代码函数,希望些函数对各位朋友有帮助,此函数只能过滤一些敏感的sql命令了,像id=1这种大家还是需要自己简单过滤了。
 代码如下 复制代码


if (!get_magic_quotes_gpc())
{
if (!empty($_GET))
{
$_GET  = addslashes_deep($_GET);
}
if (!empty($_POST))
{
$_POST = addslashes_deep($_POST);
}

$_COOKIE   = addslashes_deep($_COOKIE);
$_REQUEST  = addslashes_deep($_REQUEST);
}

function addslashes_deep($value)
{
if (empty($value))
{
return $value;
}
else
{
return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
}
}

验证码可以防止一些用户重复提交来猜密码或利用暴力工具来猜密码,我们加了验证码之后给他们增加了不少难度了,下面我提供一款基于session验证码程序。


在网站的登陆和注册的时候,经常会用到验证码来防止别人用机械暴力注册或登陆,加上验证码这样一定程度上让网站安全很多,下面是一个比较简单的验证码生成,同时给session赋值。

 代码如下 复制代码

<?php
session_start();
header(“Content-type: image/png”);
//创建真彩色白纸
$im = @imagecreatetruecolor(50, 20) or die(“建立图像失败”);
//获取背景颜色
$background_color = imagecolorallocate($im, 255, 255, 255);
//填充背景颜色(这个东西类似油桶)
imagefill($im,0,0,$background_color);
//获取边框颜色
$border_color = imagecolorallocate($im,200,200,200);
//画矩形,边框颜色200,200,200
imagerectangle($im,0,0,49,19,$border_color);

//逐行炫耀背景,全屏用1或0
for($i=2;$i<18;$i++){
//获取随机淡色
$line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
//画线
imageline($im,2,$i,47,$i,$line_color);
}

//设置字体大小
$font_size=12;

//设置印上去的文字
$Str[0] = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
$Str[1] = “abcdefghijklmnopqrstuvwxyz”;
$Str[2] = “01234567891234567890123456″;

//获取第1个随机文字
$imstr[0]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[0]["x"] = rand(2,5);
$imstr[0]["y"] = rand(1,4);

//获取第2个随机文字
$imstr[1]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
$imstr[1]["y"] = rand(1,3);

//获取第3个随机文字
$imstr[2]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1);
$imstr[2]["y"] = rand(1,4);

//获取第4个随机文字
$imstr[3]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0,1);
$imstr[3]["y"] = rand(1,3);

//将显示的数组赋值给session
$_SESSION['CODE'] = $imstr[0]["s"].$imstr[1]["s"].$imstr[2]["s"].$imstr[3]["s"];

//写入随机字串
for($i=0;$i<4;$i++){
$text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180));
imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color);
}
//显示图片
imagepng($im);
//销毁图片
imagedestroy($im);
?>

php网站被挂木马修复是次要的最要的是怎么修复之后不再让木马再注入到你的网站才是重要的,下面我来总结一下php网站被挂木马修复与之后防止网站再次给挂木马的方法。

在linux中我们可以使用命令来搜查木马文件,到代码安装目录执行下面命令

 代码如下 复制代码

find ./ -iname "*.php" | xargs grep -H -n "eval(base64_decode"

搜出来接近100条结果,这个结果列表很重要,木马都在里面,要一个一个文件打开验证是否是木马,如果是,马上删除掉

最后找到10个木马文件,存放在各种目录,都是php webshell,功能很齐全,用base64编码

如果你在windows中查找目录直接使用windows文件搜索就可以了,可以搜索eval或最近修改文件,然后如果是dedecms我们要查看最新dedecms漏洞呀然后修补。


下面给个php木马查找工具,直接放到你站点根目录

 代码如下 复制代码

<?php

/**************PHP Web木马扫描器************************/

/* [+] 作者: alibaba */

/* [+] QQ: 1499281192 * www.111cn.net/

/* [+] MSN: weeming21@hotmail.com */

/* [+] 首发: t00ls.net , 转载请注明t00ls */

/* [+] 版本: v1.0 */

/* [+] 功能: web版php木马扫描工具*/

/* [+] 注意: 扫描出来的文件并不一定就是后门, */

/* 请自行判断、审核、对比原文件。*/

/* 如果你不确定扫出来的文件是否为后门,*/

/* 欢迎你把该文件发给我进行分析。*/

/*******************************************************/

ob_start();

set_time_limit(0);

$username = "t00ls"; //设置用户名

$password = "t00ls"; //设置密码

$md5 = md5(md5($username).md5($password));

$version = "PHP Web木马扫描器v1.0";

 

PHP Web 木马扫描器

$realpath = realpath('./');

$selfpath = $_SERVER['PHP_SELF'];

$selfpath = substr($selfpath, 0, strrpos($selfpath,'/'));

define('REALPATH', str_replace('//','/',str_replace('\','/',substr($realpath, 0, strlen($realpath) - strlen($selfpath)))));

define('MYFILE', basename(__FILE__));

define('MYPATH', str_replace('\', '/', dirname(__FILE__)).'/');

define('MYFULLPATH', str_replace('\', '/', (__FILE__)));

define('HOST', "http://".$_SERVER['HTTP_HOST']);

?>

<html>

<head>

<title><?php echo $version?></title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<style>

body{margin:0px;}

body,td{font: 12px Arial,Tahoma;line-height: 16px;}

a {color: #00f;text-decoration:underline;}

a:hover{color: #f00;text-decoration:none;}

.alt1 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f1f1f1;padding:5px 10px 5px 5px;}

.alt2 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f9f9f9;padding:5px 10px 5px 5px;}

.focus td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 10px 5px 5px;}

.head td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#e9e9e9;padding:5px 10px 5px 5px;font-weight:bold;}

.head td span{font-weight:normal;}

</style>

</head>

<body>

<?php

if(!(isset($_COOKIE['t00ls']) && $_COOKIE['t00ls'] == $md5) && !(isset($_POST['username']) && isset($_POST['password']) && (md5(md5($_POST['username']).md5($_POST['password']))==$md5)))

{

echo '<form id="frmlogin" name="frmlogin" method="post" action="">用户名: <input type="text" name="username" id="username" /> 密码: <input type="password" name="password" id="password" /> <input type="submit" name="btnLogin" id="btnLogin" value="登陆" /></form>';

}

elseif(isset($_POST['username']) && isset($_POST['password']) && (md5(md5($_POST['username']).md5($_POST['password']))==$md5))

{

setcookie("t00ls", $md5, time()+60*60*24*365,"/");

echo "登陆成功!";

header( 'refresh: 1; url='.MYFILE.'?action=scan' );

exit();

}

else

{

setcookie("t00ls", $md5, time()+60*60*24*365,"/");

$setting = getSetting();

$action = isset($_GET['action'])?$_GET['action']:"";

 

if($action=="logout")

{

setcookie ("t00ls", "", time() - 3600);

Header("Location: ".MYFILE);

exit();

}

if($action=="download" && isset($_GET['file']) && trim($_GET['file'])!="")

{

$file = $_GET['file'];

ob_clean();

if (@file_exists($file)) {

header("Content-type: application/octet-stream");

header("Content-Disposition: filename="".basename($file).""");

echo file_get_contents($file);

}

exit();

}

?>

<table border="0" cellpadding="0" cellspacing="0" width="100%">

<tbody><tr class="head">

<td><?php echo $_SERVER['SERVER_ADDR']?><span style="float: right; font-weight:bold;"><?php echo "<a href='http://www.t00ls.net/'>$version</a>"?></span></td>

</tr>

<tr class="alt1">

<td><span style="float: right;"><?=date("Y-m-d H:i:s",mktime())?></span>

<a href="?action=scan">扫描</a> |

<a href="?action=setting">设定</a> |

<a href="?action=logout">登出</a>

</td>

</tr>

</tbody></table>

<br>

<?php

if($action=="setting")

{

if(isset($_POST['btnsetting']))

{

$Ssetting = array();

$Ssetting['user']=isset($_POST['checkuser'])?$_POST['checkuser']:"php | php? | phtml";

$Ssetting['all']=isset($_POST['checkall'])&&$_POST['checkall']=="on"?1:0;

$Ssetting['hta']=isset($_POST['checkhta'])&&$_POST['checkhta']=="on"?1:0;

setcookie("t00ls_s", base64_encode(serialize($Ssetting)), time()+60*60*24*365,"/");

echo "设置完成!";

header( 'refresh: 1; url='.MYFILE.'?action=setting' );

exit();

}

?>

<form name="frmSetting" method="post" action="?action=setting">

<FIELDSET style="width:400px">

<LEGEND>扫描设定</LEGEND>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="60">文件后缀:</td>

<td width="300"><input type="text" name="checkuser" id="checkuser" style="width:300px;" value="<?php echo $setting['user']?>"></td>

</tr>

<tr>

<td><label for="checkall">所有文件</label></td>

<td><input type="checkbox" name="checkall" id="checkall" <?php if($setting['all']==1) echo "checked"?>></td>

</tr>

<tr>

<td><label for="checkhta">设置文件</label></td>

<td><input type="checkbox" name="checkhta" id="checkhta" <?php if($setting['hta']==1) echo "checked"?>></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>

<input type="submit" name="btnsetting" id="btnsetting" value="提交">

</td>

</tr>

</table>

</fieldset>

</form>

<?php

}

else

{

$dir = isset($_POST['path'])?$_POST['path']:MYPATH;

$dir = substr($dir,-1)!="/"?$dir."/":$dir;

?>

<form name="frmScan" method="post" action="">

<table width="100%%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="35" style="vertical-align:middle; padding-left:5px;">扫描路径:</td>

<td width="690">

<input type="text" name="path" id="path" style="width:600px" value="<?php echo $dir?>">

&nbsp;&nbsp;<input type="submit" name="btnScan" id="btnScan" value="开始扫描"></td>

</tr>

</table>

</form>

<?php

if(isset($_POST['btnScan']))

{

$start=mktime();

$is_user = array();

$is_ext = "";

$list = "";

 

if(trim($setting['user'])!="")

{

$is_user = explode("|",$setting['user']);

if(count($is_user)>0)

{

foreach($is_user as $key=>$value)

$is_user[$key]=trim(str_replace("?","(.)",$value));

$is_ext = "(.".implode("($|.))|(.",$is_user)."($|.))";

}

}

if($setting['hta']==1)

{

$is_hta=1;

$is_ext = strlen($is_ext)>0?$is_ext."|":$is_ext;

$is_ext.="(^.htaccess$)";

}

if($setting['all']==1 || (strlen($is_ext)==0 && $setting['hta']==0))

{

$is_ext="(.+)";

}

 

$php_code = getCode();

if(!is_readable($dir))

$dir = MYPATH;

$count=$scanned=0;

scan($dir,$is_ext);

$end=mktime();

$spent = ($end - $start);

?>

<div style="padding:10px; background-color:#ccc">扫描: <?php echo $scanned?> 文件| 发现: <?php echo $count?> 可疑文件| 耗时: <?php echo $spent?> 秒</div>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr class="head">

<td width="15" align="center">No.</td>

<td width="48%">文件</td>

<td width="12%">更新时间</td>

<td width="10%">原因</td>

<td width="20%">特征</td>

<td>动作</td>

</tr>

<?php echo $list?>

</table>

<?php

}

}

}

ob_flush();

?>

</body>

</html>

<?php

function scan($path = '.',$is_ext){

global $php_code,$count,$scanned,$list;

$ignore = array('.', '..' );

$replace=array(" ","n","r","t");

$dh = @opendir( $path );

 

 

while(false!==($file=readdir($dh))){

if( !in_array( $file, $ignore ) ){

if( is_dir( "$path$file" ) ){

scan("$path$file/",$is_ext);

} else {

$current = $path.$file;

if(MYFULLPATH==$current) continue;

if(!preg_match("/$is_ext/i",$file)) continue;

if(is_readable($current))

{

$scanned++;

$content=file_get_contents($current);

$content= str_replace($replace,"",$content);

foreach($php_code as $key => $value)

{

if(preg_match("/$value/i",$content))

{

$count++;

$j = $count % 2 + 1;

$filetime = date('Y-m-d H:i:s',filemtime($current));

$reason = explode("->",$key);

$url = str_replace(REALPATH,HOST,$current);

preg_match("/$value/i",$content,$arr);

$list.="

<tr class='alt$j' onmouseover='this.className="focus";' onmouseout='this.className="alt$j";'>

<td>$count</td>

<td><a href='$url' target='_blank'>$current</a></td>

<td>$filetime</td>

<td><font color=red>$reason[0]</font></td>

<td><font color=#090>$reason[1]</font></td>

<td><a href='?action=download&file=$current' target='_blank'>下载</a></td>

</tr>";

//echo $key . "-" . $path . $file ."(" . $arr[0] . ")" ."<br />";

//echo $path . $file ."<br />";

break;

}

}

}

}

}

}

closedir( $dh );

}

function getSetting()

{

$Ssetting = array();

if(isset($_COOKIE['t00ls_s']))

{

$Ssetting = unserialize(base64_decode($_COOKIE['t00ls_s']));

$Ssetting['user']=isset($Ssetting['user'])?$Ssetting['user']:"php | php? | phtml | shtml";

$Ssetting['all']=isset($Ssetting['all'])?intval($Ssetting['all']):0;

$Ssetting['hta']=isset($Ssetting['hta'])?intval($Ssetting['hta']):1;

}

else

{

$Ssetting['user']="php | php? | phtml | shtml";

$Ssetting['all']=0;

$Ssetting['hta']=1;

setcookie("t00ls_s", base64_encode(serialize($Ssetting)), time()+60*60*24*365,"/");

}

return $Ssetting;

}

function getCode()

{

return array(

'后门特征->cha88.cn'=>'cha88.cn',

'后门特征->c99shell'=>'c99shell',

'后门特征->phpspy'=>'phpspy',

'后门特征->Scanners'=>'Scanners',

'后门特征->cmd.php'=>'cmd.php',

'后门特征->str_rot13'=>'str_rot13',

'后门特征->webshell'=>'webshell',

'后门特征->EgY_SpIdEr'=>'EgY_SpIdEr',

'后门特征->tools88.com'=>'tools88.com',

'后门特征->SECFORCE'=>'SECFORCE',

'后门特征->eval("?>'=>'eval(('|")?>',

'可疑代码特征->system('=>'system(',

'可疑代码特征->passthru('=>'passthru(',

'可疑代码特征->shell_exec('=>'shell_exec(',

'可疑代码特征->exec('=>'exec(',

'可疑代码特征->popen('=>'popen(',

'可疑代码特征->proc_open'=>'proc_open',

'可疑代码特征->eval($'=>'eval(('|"|s*)\$',

'可疑代码特征->assert($'=>'assert(('|"|s*)\$',

'危险MYSQL代码->returns string soname'=>'returnsstringsoname',

'危险MYSQL代码->into outfile'=>'intooutfile',

'危险MYSQL代码->load_file'=>'select(s+)(.*)load_file',

'加密后门特征->eval(gzinflate('=>'eval(gzinflate(',

'加密后门特征->eval(base64_decode('=>'eval(base64_decode(',

'加密后门特征->eval(gzuncompress('=>'eval(gzuncompress(',

'加密后门特征->eval(gzdecode('=>'eval(gzdecode(',

'加密后门特征->eval(str_rot13('=>'eval(str_rot13(',

'加密后门特征->gzuncompress(base64_decode('=>'gzuncompress(base64_decode(',

'加密后门特征->base64_decode(gzuncompress('=>'base64_decode(gzuncompress(',

'一句话后门特征->eval($_'=>'eval(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->assert($_'=>'assert(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->require($_'=>'require(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->require_once($_'=>'require_once(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->include($_'=>'include(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->include_once($_'=>'include_once(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->call_user_func("assert"'=>'call_user_func(("|')assert("|')',

'一句话后门特征->call_user_func($_'=>'call_user_func(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'一句话后门特征->$_POST/GET/REQUEST/COOKIE[?]($_POST/GET/REQUEST/COOKIE[?]'=>'$_(POST|GET|REQUEST|COOKIE)[([^]]+)](('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[',

'一句话后门特征->echo(file_get_contents($_POST/GET/REQUEST/COOKIE'=>'echo(file_get_contents(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'上传后门特征->file_put_contents($_POST/GET/REQUEST/COOKIE,$_POST/GET/REQUEST/COOKIE'=>'file_put_contents(('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[([^]]+)],('|"|s*)\$_(POST|GET|REQUEST|COOKIE)',

'上传后门特征->fputs(fopen("?","w"),$_POST/GET/REQUEST/COOKIE['=>'fputs(fopen((.+),('|")w('|")),('|"|s*)\$_(POST|GET|REQUEST|COOKIE)[',

'.htaccess插马特征->SetHandler application/x-httpd-php'=>'SetHandlerapplication/x-httpd-php',

'.htaccess插马特征->php_value auto_prepend_file'=>'php_valueauto_prepend_file',

'.htaccess插马特征->php_value auto_append_file'=>'php_valueauto_append_file'

);

}

?>

今天没事与了一个Php Aes加密类程序,适用于Yii的扩展如果不用在Yii框架中,把代码中Yii::app()->params[\'encryptKey\'] 换成你对应的默认key就可以了。

AES加密算法 – 算法原理

AES 算法基于排列和置换运算。排列是对数据重新进行安排,置换是将一个数据单元替换为另一个。AES 使用几种不同的方法来执行排列和置换运算。
AES 是一个迭代的、对称密钥分组的密码,它可以使用128、192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据。与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据。通过分组密码返回的加密数据的位数与输入数据相同。迭代加密使用一个循环结构,在该循环中重复置换和替换输入数据。

 代码如下 复制代码

<?php
/**
* php AES加解密类
* 因为java只支持128位加密,所以php也用128位加密,可以与java互转。
* 同时AES的标准也是128位。只是RIJNDAEL算法可以支持128,192和256位加密。
*
* @author Terry
*
*/
class PhpAes
{
/**
* This was AES-128 / CBC / ZeroBytePadding encrypted.
* return base64_encode string
* @author Terry
* @param string $plaintext
* @param string $key
*/
public static function AesEncrypt($plaintext,$key = null)
{
if ($plaintext == '') return '';
if(!extension_loaded('mcrypt'))
throw new CException(Yii::t('yii','AesEncrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$plaintext = self::PKCS5Padding($plaintext, $size);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$key=self::substr($key===null ? Yii::app()->params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* on Windows instead */
$iv = substr(md5($key),0,mcrypt_enc_get_iv_size($module));
/* Intialize encryption */
mcrypt_generic_init($module, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($module, $plaintext);

/* Terminate encryption handler */
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return base64_encode(trim($encrypted));
}

/**
* This was AES-128 / CBC / ZeroBytePadding decrypted.
* @author Terry
* @param string $encrypted base64_encode encrypted string
* @param string $key
* @throws CException
* @return string
*/
public static function AesDecrypt($encrypted, $key = null)
{
if ($encrypted == '') return '';
if(!extension_loaded('mcrypt'))
throw new CException(Yii::t('yii','AesDecrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));

$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$key=self::substr($key===null ? Yii::app()->params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));

$iv = substr(md5($key),0,mcrypt_enc_get_iv_size($module));

/* Initialize encryption module for decryption */
mcrypt_generic_init($module, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($module, $ciphertext_dec);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return self::UnPKCS5Padding($decrypted);
}


private static function strlen($string)
{
return extension_loaded('mbstring') ? mb_strlen($string,'8bit') : strlen($string);
}

private static function substr($string,$start,$length)
{
return extension_loaded('mbstring') ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
}

private static function PKCS5Padding ($text, $blocksize) {
$pad = $blocksize - (self::strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}

private static function UnPKCS5Padding($text)
{
$pad = ord($text{self::strlen($text)-1});
if ($pad > self::strlen($text)) return false;
if (strspn($text, chr($pad), self::strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
}

使用方法

 代码如下 复制代码

<?php
require_once('./AES.php');
//$aes = new AES();
$aes = new AES(true);// 把加密后的字符串按十六进制进行存储
//$aes = new AES(true,true);// 带有调试信息且加密字符串按十六进制存储
$key = "this is a 32 byte key";// 密钥
$keys = $aes->makeKey($key);
$encode = "123456";// 被加密的字符串
$ct = $aes->encryptString($encode, $keys);
echo "encode = ".$ct."<br>";
$cpt = $aes->decryptString($ct, $keys);
echo "decode = ".$cpt;
?>

在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组。所以,这里主要探讨php输入流php://input

对一php://input介绍,PHP官方手册文档有一段话对它进行了很明确地概述。

“php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype=”multipart/form-data”.

翻译过来,是这样:

“php://input可以读取没有处理过的POST数据。相较于$HTTP_RAW_POST_DATA而言,它给内存带来的压力较小,并且不需要特殊的php.ini设置。php://input不能用于enctype=multipart/form-data”


我们应该怎么去理解这段概述呢?!我把它划分为三部分,逐步去理解。

读取POST数据
不能用于multipart/form-data类型
php://input VS $HTTP_RAW_POST_DATA
读取POST数据
PHPer们一定很熟悉$_POST这个内置变量。$_POST与php://input存在哪些关联与区别呢?另外,客户端向服务端交互数据,最常用的方法除了POST之外,还有GET。既然php://input作为PHP输入流,它能读取GET数据吗?这二个问题正是我们这节需要探讨的主要内容。
经验告诉我们,从测试与观察中总结,会是一个很凑效的方法。这里,我写了几个脚本来帮助我们测试。

@file 192.168.0.6:/phpinput_server.php 打印出接收到的数据
@file 192.168.0.8:/phpinput_post.php 模拟以POST方法提交表单数据
@file 192.168.0.8:/phpinput_xmlrpc.php 模拟以POST方法发出xmlrpc请求.
@file 192.168.0.8:/phpinput_get.php 模拟以GET方法提交表单表数
phpinput_server.php与phpinput_post.php

 

 代码如下 复制代码
<?php
//@file phpinput_server.php
$raw_post_data = file_get_contents('php://input', 'r');
echo "-------$_POST------------------n";
echo var_dump($_POST) . "n";
echo "-------php://input-------------n";
echo $raw_post_data . "n";
?>
 
<?php
//@file phpinput_post.php
$http_entity_body = 'n=' . urldecode('perfgeeks') . '&amp;p=' . urldecode('7788');
$http_entity_type = 'application/x-www-form-urlencoded';
$http_entity_length = strlen($http_entity_body);
$host = '192.168.0.6';
$port = 80;
$path = '/phpinput_server.php';
$fp = fsockopen($host, $port, $error_no, $error_desc, 30);
if ($fp) {
  fputs($fp, "POST {$path} HTTP/1.1rn");
  fputs($fp, "Host: {$host}rn");
  fputs($fp, "Content-Type: {$http_entity_type}rn");
  fputs($fp, "Content-Length: {$http_entity_length}rn");
  fputs($fp, "Connection: closernrn");
  fputs($fp, $http_entity_body . "rnrn");
 
  while (!feof($fp)) {
    $d .= fgets($fp, 4096);
  }
  fclose($fp);
  echo $d;
}
?>


我们可以通过使用工具ngrep抓取http请求包(因为我们需要探知的是php://input,所以我们这里只抓取http Request数据包)。我们来执行测试脚本phpinput_post.php

 代码如下 复制代码
@php /phpinput_post.php
HTTP/1.1 200 OK
Date: Thu, 08 Apr 2010 03:23:36 GMT
Server: Apache/2.2.3 (CentOS)
X-Powered-By: PHP/5.1.6
Content-Length: 160
Connection: close
Content-Type: text/html; charset=UTF-8
-------$_POST------------------
array(2) {
  ["n"]=> string(9) "perfgeeks"
  ["p"]=> string(4) "7788"
}
-------php://input-------------
n=perfgeeks&p=7788

通过ngrep抓到的http请求包如下:

T 192.168.0.8:57846 -> 192.168.0.6:80 [AP]
  POST /phpinput_server.php HTTP/1.1..
  Host: 192.168.0.6..Content-Type: application/x-www-form-urlencoded..Co
  ntent-Length: 18..Connection: close....n=perfgeeks&p=7788....
仔细观察,我们不难发现
1,$_POST数据,php://input 数据与httpd entity body数据是“一致”的
2,http请求中的Content-Type是application/x-www-form-urlencoded ,它表示http请求body中的数据是使用http的post方法提交的表单数据,并且进行了urlencode()处理。
(注:注意加粗部分内容,下文不再提示).

[!--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
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • cmd下过滤文件名称的两种方法

    这篇文章主要介绍了cmd下过滤文件名称的两种方法,需要的朋友可以参考下...2020-06-30
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25