首页 > 编程技术 > php

php 防止恶意刷新页面方法总结

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

恶意刷新就是不停的去刷新提交页面,导致大量无效数据了,下面我们来总结一下php 防止恶意刷新页面方法总结

防止恶意刷页面的原理是

要求在页面间传递一个验证字符串,
在生成页面的时候   随机产生一个字符串,
做为一个必须参数在所有连接中传递。同时将这个字符串保存在session中。

点连接或者表单进入页面后,判断session中的验证码是不是与用户提交的相同,如果相同,则处理,不相同则认为是重复刷新。
在处理完成后将重新生成一个验证码,用于新页面的生成

代码

 代码如下 复制代码

<?php
session_start();
$k=$_GET['k'];
$t=$_GET['t'];
$allowTime = 1800;//防刷新时间
$ip = get_client_ip();
$allowT = md5($ip.$k.$t);
if(!isset($_SESSION[$allowT]))
{
$refresh = true;
$_SESSION[$allowT] = time();
}elseif(time() - $_SESSION[$allowT]>$allowTime){
$refresh = true;
$_SESSION[$allowT] = time();
}else{
$refresh = false;
}
?>

ie6提交两次我也碰到过,大致是用图片代替submit时,图片上有个submit(),这样会提交两次,如果只是submit钮我没碰到过提交两次的情况。

现在整理一下:
方法基本上前面几位说得差不多
接收的页即2.php分为两部分,一部分处理提交过来的变量,一部分显示页面
处理变量完毕用header( "location: ".$_SERVER[ 'PHP_SELF '])跳转到自身页
本部分要做判断,如果没有post的变量就跳过。当然也可以跳到别的页面。
跳到别的页面返回时会有问题,建议做在一个php文件里。
如果上页穿过来得变量不符合要求可以强制返回

 代码如下 复制代码
<script>
history.go(-1);
</script>

只说了一下大体思路,也许高手们不会遇到此类问题,可是并不是每个人都是高手。
2.php的流程

 代码如下 复制代码
if(isset($_POST))
{     接收变量
    if(变量不符合要求)
          <script> history.go(-1); </script>
    else
        操作数据
          ...
        if(操作完成)
          header( "location: ".$_SERVER[ 'PHP_SELF ']);
}
<script   language= "JavaScript ">  
<!--  
 javascript:window.history.forward(1);  
//-->  
</script>
php curl 太强大了,它不但可以模仿用户登录,还可以模仿用户IP地址哦,为伪造IP来源,本实例仅供参考哦。

curl发出请求的文件fake_ip.php:

代码

 代码如下 复制代码

<?php
$ch = curl_init();
  
$url = "http://localhost/target_ip.php";
  
$header = array(
  'CLIENT-IP:58.68.44.61',
  'X-FORWARDED-FOR:58.68.44.61',
);
  
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  
$page_content = curl_exec($ch);
  
curl_close($ch);
  
echo $page_content;
  
?>


请求的目标文件target_ip.php:

代码
<?php
echo getenv('HTTP_CLIENT_IP');
echo getenv('HTTP_X_FORWARDED_FOR');
echo getenv('REMOTE_ADDR');
?>

目标文件target_ip里面的IP打印顺序是目前很多开源系统的IP获取顺序
访问fake_ip.php,看到结果:
58.68.44.61
58.68.44.61
127.0.0.1

实例

CURL确实很强悍,可以伪造IP和来源。
1.php 请求 2.php 。

 代码如下 复制代码

1.php代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/2.php");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));  //构造IP
curl_setopt($ch, CURLOPT_REFERER, "http://www.111cn.net/ ");   //构造来路
curl_setopt($ch, CURLOPT_HEADER, 1);
$out = curl_exec($ch);
curl_close($ch);

2.php代码如下:

function getClientIp() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"]))
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if (!empty($_SERVER["REMOTE_ADDR"]))
        $ip = $_SERVER["REMOTE_ADDR"];
    else
        $ip = "err";
    return $ip;
}

echo "IP: " . getClientIp() . "";
echo "referer: " . $_SERVER["HTTP_REFERER"];

伪造成功,这是不是给“刷票”的朋友提供了很好的换IP的方案!!

•得到当前要处理的月份总共有多少天$days •得到当前要处理的月份的一号是星期几$dayofweek $days的作用:知道要处理的月份共有多少天,就可以通过循环输出天数了

使用PHP实现万年历功能的要点:

•得到当前要处理的月份总共有多少天$days
•得到当前要处理的月份的一号是星期几$dayofweek
$days的作用:知道要处理的月份共有多少天,就可以通过循环输出天数了

$dayofweek的作用:只有知道每个月的1号是星期几,才能知道在输出天数之前需要输出多少空格(空白)

 代码如下 复制代码

<?php
/**
 * PHP万年历
 * @author Fly 2012/10/16
 */
class Calendar{
    protected $_table;//table表格
    protected $_currentDate;//当前日期
    protected $_year;    //年
    protected $_month;    //月
    protected $_days;    //给定的月份应有的天数
    protected $_dayofweek;//给定月份的 1号 是星期几
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->_table="";
        $this->_year  = isset($_GET["y"])?$_GET["y"]:date("Y");
        $this->_month = isset($_GET["m"])?$_GET["m"]:date("m");
        if ($this->_month>12){//处理出现月份大于12的情况
            $this->_month=1;
            $this->_year++;
        }
        if ($this->_month<1){//处理出现月份小于1的情况
            $this->_month=12;
            $this->_year--;
        }
        $this->_currentDate = $this->_year.'年'.$this->_month.'月份';//当前得到的日期信息
        $this->_days           = date("t",mktime(0,0,0,$this->_month,1,$this->_year));//得到给定的月份应有的天数
        $this->_dayofweek    = date("w",mktime(0,0,0,$this->_month,1,$this->_year));//得到给定的月份的 1号 是星期几
    }
    /**
     * 输出标题和表头信息
     */
    protected function _showTitle()
    {
        $this->_table="<table><thead><tr align='center'><th colspan='7'>".$this->_currentDate."</th></tr></thead>";
        $this->_table.="<tbody><tr>";
        $this->_table .="<td style='color:red'>星期日</td>";
        $this->_table .="<td>星期一</td>";
        $this->_table .="<td>星期二</td>";
        $this->_table .="<td>星期三</td>";
        $this->_table .="<td>星期四</td>";
        $this->_table .="<td>星期五</td>";
        $this->_table .="<td style='color:red'>星期六</td>";
        $this->_table.="</tr>";
    }
    /**
     * 输出日期信息
     * 根据当前日期输出日期信息
     */
    protected function _showDate()
    {
        $nums=$this->_dayofweek+1;
        for ($i=1;$i<=$this->_dayofweek;$i++){//输出1号之前的空白日期
            $this->_table.="<td>&nbsp</td>";
        }
        for ($i=1;$i<=$this->_days;$i++){//输出天数信息
            if ($nums%7==0){//换行处理:7个一行
                $this->_table.="<td>$i</td></tr><tr>";   
            }else{
                $this->_table.="<td>$i</td>";
            }
            $nums++;
        }
        $this->_table.="</tbody></table>";
        $this->_table.="<h3><a href='?y=".($this->_year)."&m=".($this->_month-1)."'>上一月</a>&nbsp;&nbsp;&nbsp;";
        $this->_table.="<a href='?y=".($this->_year)."&m=".($this->_month+1)."'>下一月</a></h3>";
    }
    /**
     * 输出日历
     */
    public function showCalendar()
    {
        $this->_showTitle();
        $this->_showDate();
        echo $this->_table;
    }
}
$calc=new Calendar();
$calc->showCalendar();

检查文件或目录是否存在 ,我们使用了php中常用的函数file_exists,这个函数就可以实现我想要的功能,下面大家慢慢参考一下。

下面是一个简单的检查文件是否存在的实例代码:

 代码如下 复制代码

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

如果文件存在,执行该 PHP 文件的显示结果是:

The file C:blablaphphello.txt exists.

如果文件不存在,执行该 PHP 文件的显示结果是:

The file C:blablaphphello.txt does not exist.

你也可以用file_exists 函数测试某个目录是否存在,示例代码如下:

 代码如下 复制代码

if (file_exists("C:\blabla\php"))
  {echo "yes";}
else
  {echo "no";}


实例

 代码如下 复制代码

/**
 * 文件或目录权限检查函数
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。
 *                          返回值在二进制计数法中,四位由高到低分别代表
 *                          可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path)
{
    /* 如果不存在,则不可读、不可写、不可改 */
    if (!file_exists($file_path))
    {
        return false;
    }
    $mark = 0;
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
    {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';
        /* 如果是目录 */
        if (is_dir($file_path))
        {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false)
            {
                return $mark; //如果目录打开失败,直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false)
            {
                $mark ^= 1; //目录可读 001,目录不可读 000
            }
            @closedir($dir);
            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false)
            {
                return $mark; //如果目录中的文件创建失败,返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false)
            {
                $mark ^= 2; //目录可写可读011,目录可写不可读 010
            }
            @fclose($fp);
            @unlink($test_file);
            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false)
            {
                return $mark;
            }
            if (@fwrite($fp, "modify test.rn") !== false)
            {
                $mark ^= 4;
            }
            @fclose($fp);
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
            @unlink($test_file);
        }
        /* 如果是文件 */
        elseif (is_file($file_path))
        {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp)
            {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);
            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false)
            {
                $mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
            }
            @fclose($fp);
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
        }
    }
    else
    {
        if (@is_readable($file_path))
        {
            $mark ^= 1;
        }
        if (@is_writable($file_path))
        {
            $mark ^= 14;
        }
    }
    return $mark;
}


 

PHP判断目录是否存在    

 代码如下 复制代码

/****************************************************
     * 将xml数据流,写入到xml文件
     * @param $xmlData
     * @return bool|string
     */
    function writeXmlFile($xmlData)
    {
        $time = time(); //获取时间戳,用于给文件命名
        $path = dirname(__FILE__); //获取当前绝对路径
        $path = substr_replace($path, "", stripos($path, "actions\data")); //将此文件所在的固有路径替换成空
        $path .= "xmlFiles\"; //存放目录名

        /*判断目标目录是否存在,不存在则新建*/
        if(!is_dir($path))
        {
            mkdir($path); //新建目录
        }

        /*记录完整路径和文件名*/
        $filePathAndName = $path.$time.".xml";

        /*打开文件,文件名为<时间戳> + <.xml>*/
        $fp = fopen($filePathAndName, "w");
        if(!$fp)
        {
            return false;
        }

        /*写入文件流*/
        $flag = fwrite($fp, $xmlData);
        if(!$flag)
        {
            return false;
        }

        fclose($fp);

        return $filePathAndName;
    }

本文章详细的总结了php利用正则过滤链接、标签,空格,换行符程序,有需要学习的朋友可参考一下。


strip_tags函数

strip_tags --- 去除字串中的HTML和PHP标签

语法 : string strip_tags (string str [, string allowable_tags])

 代码如下 复制代码

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

正则过滤各种标签,空格,换行符

 代码如下 复制代码

$str=preg_replace("/s+/", " ", $str); //过滤多余回车
$str=preg_replace("/<[ ]+/si","<",$str); //过滤<__("<"号后面带空格)
$str=preg_replace("/<!–.*?–>/si","",$str); //注释
$str=preg_replace("/<(!.*?)>/si","",$str); //过滤DOCTYPE
$str=preg_replace("/<(/?html.*?)>/si","",$str); //过滤html标签
$str=preg_replace("/<(/?head.*?)>/si","",$str); //过滤head标签
$str=preg_replace("/<(/?meta.*?)>/si","",$str); //过滤meta标签
$str=preg_replace("/<(/?body.*?)>/si","",$str); //过滤body标签
$str=preg_replace("/<(/?link.*?)>/si","",$str); //过滤link标签
$str=preg_replace("/<(/?form.*?)>/si","",$str); //过滤form标签
$str=preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签
$str=preg_replace("/<(applet.*?)>(.*?)<(/applet.*?)>/si","",$str); //过滤applet标签
$str=preg_replace("/<(/?applet.*?)>/si","",$str); //过滤applet标签
$str=preg_replace("/<(style.*?)>(.*?)<(/style.*?)>/si","",$str); //过滤style标签
$str=preg_replace("/<(/?style.*?)>/si","",$str); //过滤style标签
$str=preg_replace("/<(title.*?)>(.*?)<(/title.*?)>/si","",$str); //过滤title标签
$str=preg_replace("/<(/?title.*?)>/si","",$str); //过滤title标签
$str=preg_replace("/<(object.*?)>(.*?)<(/object.*?)>/si","",$str); //过滤object标签
$str=preg_replace("/<(/?objec.*?)>/si","",$str); //过滤object标签
$str=preg_replace("/<(noframes.*?)>(.*?)<(/noframes.*?)>/si","",$str); //过滤noframes标签
$str=preg_replace("/<(/?noframes.*?)>/si","",$str); //过滤noframes标签
$str=preg_replace("/<(i?frame.*?)>(.*?)<(/i?frame.*?)>/si","",$str); //过滤frame标签
$str=preg_replace("/<(/?i?frame.*?)>/si","",$str); //过滤frame标签
$str=preg_replace("/<(script.*?)>(.*?)<(/script.*?)>/si","",$str); //过滤script标签
$str=preg_replace("/<(/?script.*?)>/si","",$str); //过滤script标签
$str=preg_replace("/javascript/si","Javascript",$str); //过滤script标签
$str=preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签
$str=preg_replace("/on([a-z]+)s*=/si","On\1=",$str); //过滤script标签
$str=preg_replace("/&#/si","&#",$str); //过滤script标签

php 正则过滤html 的超链接

 代码如下 复制代码
<?php
echo preg_replace("/(?<=href=)([^>]*)(?=>)/i","#", "<a href='www.111cn.net'>你好,点这里看看</a><a href='www.111cn.net'>你好,点这里看看</a>");
?>

正则:/(?<=href=)([^>]*)(?=>)/
(?<=exp) 匹配exp后面的位置
(?=exp) 匹配exp前面的位置
此正则 匹配 在 href= 之后 “>” 之前 的 非 “>” 的所有字符
例子:<a href='www.111cn.net'>
找到这些字符(url)用 # 替换,就可以去掉html里的所有链接。

标签:[!--infotagslink--]

您可能感兴趣的文章: