首页 > 编程技术 > php

PHP 输入流 php://input使用说明(1/2)

发布时间:2016-11-25 15:23

在使用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()处理。
(注:注意加粗部分内容,下文不再提示).

今天没事与了一个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;
?>

表单提交如果安全做得不好就很容易因为这个表单提交导致网站被攻击了,下面我来分享两个常用的php 过滤表单提交的危险代码的实例,各位有需要的朋友可参考。

例1

 

 代码如下 复制代码

function uhtml($str) 

    $farr = array( 
        "/s+/", //过滤多余空白 
         //过滤 <script>等可能引入恶意内容或恶意改变显示布局的代码,如果不需要插入flash等,还

可以加入<object>的过滤 
        "/<(/?)(script|i?frame|style|html|body|title|link|meta|?|%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+s*=([^>]*>)/isU",//过滤javascript的on事件 
   ); 
   $tarr = array( 
        " ", 
        "<123>",//如果要直接清除不安全的标签,这里可以留空 
        "12", 
   ); 
  $str = preg_replace( $farr,$tarr,$str); 
   return $str; 
}

例2
或者这样操作

 代码如下 复制代码

//get post data
 function PostGet($str,$post=0)
 {
  empty($str)?die('para is null'.$str.'!'):'';
  
  if( $post )
  {
   if( get_magic_quotes_gpc() )
   {
    return htmlspecialchars(isset($_POST[$str])?$_POST

[$str]:'');
   }
   else
   {
    return addslashes(htmlspecialchars(isset($_POST[$str])?

$_POST[$str]:''));
   }
   
  }
  else
  {
   if( get_magic_quotes_gpc() )
   {
    return htmlspecialchars(isset($_GET[$str])?$_GET[$str]:''); 
   }
   else
   {
    return addslashes(htmlspecialchars(isset($_GET[$str])?

$_GET[$str]:'')); 
   }
  }
 }

CC攻击就是对方利用程序或一些代理对您的网站进行不间断的访问,造成您的网站处理不了而处于当机状态,下面我们来总结一些防CC攻击的php实例代码,各位朋友可参考。

例1

 代码如下 复制代码

//代理IP直接退出
empty($_SERVER['HTTP_VIA']) or exit('Access Denied');
//防止快速刷新
session_start();
$seconds = '3'; //时间段[秒]
$refresh = '5'; //刷新次数
//设置监控变量
$cur_time = time();
if(isset($_SESSION['last_time'])){
    $_SESSION['refresh_times'] += 1;
}else{
    $_SESSION['refresh_times'] = 1;
    $_SESSION['last_time'] = $cur_time;
}
//处理监控结果
if($cur_time - $_SESSION['last_time'] < $seconds){
    if($_SESSION['refresh_times'] >= $refresh){
        //跳转至攻击者服务器地址
        header(sprintf('Location:%s', 'http://127.0.0.1'));
        exit('Access Denied');
    }
}else{
    $_SESSION['refresh_times'] = 0;
    $_SESSION['last_time'] = $cur_time;
}

例二

 

 代码如下 复制代码

$P_S_T = $t_array[0] + $t_array[1];
$timestamp = time();

session_start();
$ll_nowtime = $timestamp ;
if (session_is_registered('ll_lasttime')){
$ll_lasttime = $_SESSION['ll_lasttime'];
$ll_times = $_SESSION['ll_times'] + 1;
$_SESSION['ll_times'] = $ll_times;
}else{
$ll_lasttime = $ll_nowtime;
$ll_times = 1;
$_SESSION['ll_times'] = $ll_times;
$_SESSION['ll_lasttime'] = $ll_lasttime;
}
if (($ll_nowtime - $ll_lasttime)<3){
if ($ll_times>=5){
header(sprintf("Location: %s",'http://127.0.0.1'));
exit;
}
}else{
$ll_times = 0;
$_SESSION['ll_lasttime'] = $ll_nowtime;
$_SESSION['ll_times'] = $ll_times;
}

一个实例我自己亲测的

日志分析

[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:13] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:12] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:11] [client 61.217.192.39] /index.php
[2011-04-16 03:03:10] [client 61.217.192.39] /index.php
[2011-04-16 03:03:10] [client 61.217.192.39] /index.php

下面是PHP方法:将以下代码另存为php文件,然后首行include入你的common.php文件中。

 代码如下 复制代码

<?php
/*
 * 防CC攻击郁闷到死,不死版。
 *
 * 如果每秒内网站刷新次数超过2次,延迟5秒后访问。
 */
 
$cc_min_nums = '1';                    //次,刷新次数
$cc_url_time = '5';                    //秒,延迟时间
//$cc_log = 'cc_log.txt';                //启用本行为记录日志
$cc_forward = 'http://localhost';    //释放到URL

//--------------------------------------------

//返回URL
$cc_uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
$site_url = 'http://'.$_SERVER ['HTTP_HOST'].$cc_uri;

//启用session
if( !isset( $_SESSION ) ) session_start();
$_SESSION["visiter"] = true;
if ($_SESSION["visiter"] <> true){
 echo "<script>setTimeout("window.location.href ='$cc_forward';", 1);</script>";
 //header("Location: ".$cc_forward);
 exit;
}

$timestamp = time();
$cc_nowtime = $timestamp ;
if (session_is_registered('cc_lasttime')){
 $cc_lasttime = $_SESSION['cc_lasttime'];
 $cc_times = $_SESSION['cc_times'] + 1;
 $_SESSION['cc_times'] = $cc_times;
}else{
 $cc_lasttime = $cc_nowtime;
 $cc_times = 1;
 $_SESSION['cc_times'] = $cc_times;
 $_SESSION['cc_lasttime'] = $cc_lasttime;
}

//获取真实IP
if (isset($_SERVER)){
 $real_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
 $real_ip = getenv("HTTP_X_FORWARDED_FOR");
}

//print_r($_SESSION);

//释放IP
if (($cc_nowtime - $cc_lasttime)<=0){
 if ($cc_times>=$cc_min_nums){       
 if(!empty($cc_log))    cc_log(get_ip(), $real_ip, $cc_log, $cc_uri);    //产生log
 echo "Wait please, try again later!<script>setTimeout("window.location.href ='$site_url';", 5000);</script>";
 //printf('您的刷新过快,请稍后。');
 //header("Location: ".$cc_forward);
 exit;
 }
}else{
 $cc_times = 0;
 $_SESSION['cc_lasttime'] = $cc_nowtime;
 $_SESSION['cc_times'] = $cc_times;
}

//记录cc日志
function cc_log($client_ip, $real_ip, $cc_log, $cc_uri){   
 $temp_time = date("Y-m-d H:i:s", time() + 3600*8);
 
 $temp_result = "[".$temp_time."] [client ".$client_ip."] ";   
 if($real_ip) $temp_result .= " [real ".$real_ip."] ";
 $temp_result .= $cc_uri . "rn";
 
 $handle = fopen ("$cc_log", "rb");
 $oldcontent = fread($handle,filesize("$cc_log"));
 fclose($handle);
 
 $newcontent = $temp_result . $oldcontent;
 $fhandle=fopen("$cc_log", "wb");
 fwrite($fhandle,$newcontent,strlen($newcontent));
 fclose($fhandle);
}

//获取在线IP
function get_ip() {
 global $_C;
 
 if(empty($_C['client_ip'])) {
 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
 $client_ip = getenv('HTTP_CLIENT_IP');
 } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
 $client_ip = getenv('HTTP_X_FORWARDED_FOR');
 } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
 $client_ip = getenv('REMOTE_ADDR');
 } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
 $client_ip = $_SERVER['REMOTE_ADDR'];
 }
 $_C['client_ip'] = $client_ip ? $client_ip : 'unknown';
 }
 return $_C['client_ip'];
}
?>

这样就可以基础工业防止了,但是如果更高级占的就没办法,大家可尝试使用相关硬件防火强来设置。

php的四个函数exec,shell_exec,system,passthru可以执行系统指令,对系统安全构成威胁,如果不用的话可以将其关闭
 代码如下 复制代码

vim /etc/php.ini

去掉disable_functions前注释,编辑内容如下

 代码如下 复制代码

disable_functions = exec,shell_exec,system,passthru,popen


友情提示,有朋友说想过滤eval函数,在php中这个不是函数无法在disable_functions禁止的哦

标签:[!--infotagslink--]

您可能感兴趣的文章: