php 跳转函数 与获取当前页面的URL地址

 更新时间:2016年11月25日 15:25  点击:1256

    function url_this(){
        $url = "http://".$_server ["http_host"].$_server["request_uri"];
        $return_url = "<a href='$url'>$url</a>";
        return $return_url;
    }

//跳转函数
function url_redirect($url,$delay=''){
 if($delay == ''){
  echo "<script>window.location.href='$url'</script>";
 }else{
  echo "<meta http-equiv='refresh' content='$delay;url=$url' />";
 }

}

} //end func

function d_addslashes($string, $force = 0) {
 if(!$globals['magic_quotes_gpc'] || $force) {
  if(is_array($string)) {
   foreach($string as $key => $val) $string[$key] = d_addslashes($val, $force);
  }
  else $string = addslashes($string);
 }
 return $string;
}
最近网站经常被攻击,后来想到了一个利用php来防止网站受攻击的办法,下面是我的代码,代码不是最好的,根据自己的需求来做,下面来看看我的代码。

/*
*网站防ip攻击代码(anti-ip attack code website)2010-11-20,ver2.0
*mydalle.com anti-refresh mechanism
*design by www.111cn.net
*/

<?php
//查询禁止ip
$ip =$_server['remote_addr'];
$fileht=".htaccess2";
if(!file_exists($fileht))file_put_contents($fileht,"");
$filehtarr=@file($fileht);
if(in_array($ip."rn",$filehtarr))die("warning:"."<br>"."your ip address are forbided by mydalle.com anti-refresh mechanism, if you have any question pls emill to shop@mydalle.com!<br>(mydalle.com anti-refresh mechanism is to enable users to have a good shipping services, but there maybe some inevitable network problems in your ip address, so that you can mail to us to solve.)");

//加入禁止ip
$time=time();
$fileforbid="log/forbidchk.dat";
if(file_exists($fileforbid))
{ if($time-filemtime($fileforbid)>30)unlink($fileforbid);
else{
$fileforbidarr=@file($fileforbid);
if($ip==substr($fileforbidarr[0],0,strlen($ip)))
{
if($time-substr($fileforbidarr[1],0,strlen($time))>120)unlink($fileforbid);
elseif($fileforbidarr[2]>120){file_put_contents($fileht,$ip."rn",file_append);unlink($fileforbid);}
else{$fileforbidarr[2]++;file_put_contents($fileforbid,$fileforbidarr);}
}
}
}
//防刷新
$str="";
$file="log/ipdate.dat";
if(!file_exists("log")&&!is_dir("log"))mkdir("log",0777);
if(!file_exists($file))file_put_contents($file,"");
$allowtime = 60;//防刷新时间
$allownum=5;//防刷新次数
$uri=$_server['request_uri'];
$checkip=md5($ip);
$checkuri=md5($uri);
$yesno=true;
$ipdate=@file($file);
foreach($ipdate as $k=>$v)
{ $iptem=substr($v,0,32);
$uritem=substr($v,32,32);
$timetem=substr($v,64,10);
$numtem=substr($v,74);
if($time-$timetem<$allowtime){
if($iptem!=$checkip)$str.=$v;
else{
$yesno=false;
if($uritem!=$checkuri)$str.=$iptem.$checkuri.$time."1rn";
elseif($numtem<$allownum)$str.=$iptem.$uritem.$timetem.($numtem+1)."rn";
else
{
if(!file_exists($fileforbid)){$addforbidarr=array($ip."rn",time()."rn",1);file_put_contents($fileforbid,$addforbidarr);}
file_put_contents("log/forbided_ip.log",$ip."--".date("y-m-d h:i:s",time())."--".$uri."rn",file_append);
$timepass=$timetem+$allowtime-$time;
die("warning:"."<br>"."pls don't refresh too frequently, and wait for ".$timepass." seconds to continue, if not your ip address will be forbided automatic by mydalle.com anti-refresh mechanism!<br>(mydalle.com anti-refresh mechanism is to enable users to have a good shipping services, but there maybe some inevitable network problems in your ip address, so that you can mail to us to solve.)");
}
}
}
}
if($yesno) $str.=$checkip.$checkuri.$time."1rn";
file_put_contents($file,$str);
?>

*/

function phpescape($str){
$sublen=strlen($str);
$restring="";
for ($i=0;$i<$sublen;$i++){
if(ord($str[$i])>=127){
$tmps教程tring=bin2hex(iconv("utf-8","ucs-2",substr($str,$i,2)));

if (!eregi("win",php_os)){
$tmpstring=substr($tmpstring,2,2).substr($tmpstring,0,2);
}
$restring.="%u".$tmpstring;
$i++;
} else {
$restring.="%".dechex(ord($str[$i]));
}
}
return $restring;
}


function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/u",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] = iconv("ucs-2","utf-8",pack("h4",substr($v,-4)));
elseif(substr($v,0,3) == "&#x")
$ar[$k] = iconv("ucs-2","utf-8",pack("h4",substr($v,3,-1)));
elseif(substr($v,0,2) == "&#") {
$ar[$k] = iconv("ucs-2","utf-8",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}


function escape($str) {
preg_match_all("/[x80-xff].|[x01-x7f]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(ord($v[0]) < 128)
$ar[$k] = rawurlencode($v);
else
$ar[$k] = "%u".bin2hex(iconv("gb2312","ucs-2",$v));
}
return join("",$ar);
}


function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/(?:%u.{4})|.+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u" && strlen($v) == 6)
$ar[$k] = iconv("ucs-2","gb2312",pack("h4",substr($v,-4)));
}
return join("",$ar);
}

 本款数据库连接类,他会自动加载sql防注入功能,过滤一些敏感的sql查询关键词,同时还可以增加判断字段 show table status的性质与show table类 获取数据库所有表名等。*/
@ini_set('mysql.trace_mode','off');
class mysql
{
 public $dblink;
 public $pconnect;
 private $search = array('/union(s*(/*.**/)?s*)+select/i', '/load_file(s*(/*.**/)?s*)+(/i', '/into(s*(/*.**/)?s*)+outfile/i');
 private $replace = array('union &nbsp; select', 'load_file &nbsp; (', 'into &nbsp; outfile');
 private $rs;

 function __construct($hostname,$username,$userpwd,$database,$pconnect=false,$charset='utf8')
 {
  define('allowed_htmltags', '<html><embed><title><meta><body><a><p><br><hr><h1><h2><h3><h4><h5><h6><font><u><i><b><strong><div><span><ol><ul><li><img><table><tr><td><map>');
  $this->pconnect=$pconnect;
  $this->dblink=$pconnect?mysql_pconnect($hostname,$username,$userpwd):mysql_connect($hostname,$username,$userpwd);
  (!$this->dblink||!is_resource($this->dblink)) && fatal_error("connect to the database unsuccessfully!");
  @mysql_unbuffered_query("set names {$charset}");
  if($this->version()>'5.0.1')
  {
   @mysql_unbuffered_query("set sql_mode = ''");
  }
  @mysql_select_db($database) or fatal_error("can not select table!");
  return $this->dblink;
 }

 function query($sql,$unbuffered=false)
 {
  //echo $sql.'<br>';
  $this->rs=$unbuffered?mysql_unbuffered_query($sql,$this->dblink):mysql_query($sql,$this->dblink);
  //(!$this->rs||!is_resource($this->rs)) && fatal_error("execute the query unsuccessfully! error:".mysql_error());
  if(!$this->rs)fatal_error('在执行sql语句 '.$sql.' 时发生以下错误:'.mysql_error());
  return $this->rs;
 }

 function fetch_one($sql)
 {
  $this->rs=$this->query($sql);
  return dircms_strips教程lashes($this->filter_pass(mysql_fetch_array($this->rs,mysql_assoc)));
 }

 function get_maxfield($filed='id',$table) // 获取$table表中$filed字段的最大值
 {
  $r=$this->fetch_one("select {$table}.{$filed} from `{$table}` order by `{$table}`.`{$filed}` desc limit 0,1");
  return $r[$filed];
 }

 function fetch_all($sql)
 {
  $this->rs=$this->query($sql);
  $result=array();
  while($rows=mysql_fetch_array($this->rs,mysql_assoc))
  {
   $result[]=$rows;
  }
  
  mysql_free_result($this->rs);
  return dircms_stripslashes($this->filter_pass($result));
 }

 function fetch_all_withkey($sql,$key='id')
 {
  $this->rs=$this->query($sql);
  $result=array();
  while($rows=mysql_fetch_array($this->rs,mysql_assoc))
  {
   $result[$rows[$key]]=$rows;
  }
  
  mysql_free_result($this->rs);
  return dircms_stripslashes($this->filter_pass($result));
 }

 function last_insert_id()
 {
  if(($insertid=mysql_insert_id($this->dblink))>0)return $insertid;
  else //如果 auto_increment 的列的类型是 bigint,则 mysql_insert_id() 返回的值将不正确.
  {
   $result=$this->fetch_one('select last_insert_id() as insertid');
   return $result['insertid'];
  }
 }

 function insert($tbname,$varray,$replace=false)
 {
  $varray=$this->escape($varray);
  $tb_fields=$this->get_fields($tbname); // mb.111cn.net 升级一下,增加判断字段是否存在
  
  foreach($varray as $key => $value)
  {
   if(in_array($key,$tb_fields))
   {
    $fileds[]='`'.$key.'`';
    $values[]=is_string($value)?'''.$value.''':$value;
   }
  }

  if($fileds)
  {
   $fileds=implode(',',$fileds);
   $fileds=str_replace(''','`',$fileds);
   $values=implode(',',$values);
   $sql=$replace?"replace into {$tbname}({$fileds}) values ({$values})":"insert into {$tbname}({$fileds}) values ({$values})";
   $this->query($sql,true);
   return $this->last_insert_id();
  }
  else return false;
 }

 function update($tbname, $array, $where = '')
 {
  $array=$this->escape($array);
  if($where)
  {
   $tb_fields=$this->get_fields($tbname); // www.111cn.net,增加判断字段是否存在
   
   $sql = '';
   foreach($array as $k=>$v)
   {
    if(in_array($k,$tb_fields))
    {
     $k=str_replace(''','',$k);
     $sql .= ", `$k`='$v'";
    }
   }
   $sql = substr($sql, 1);
   
   if($sql)$sql = "update `$tbname` set $sql where $where";
   else return true;
  }
  else
  {
   $sql = "replace into `$tbname`(`".implode('`,`', array_keys($array))."`) values('".implode("','", $array)."')";
  }
  return $this->query($sql,true);
 }
 
 function mysql_delete($tbname,$idarray,$filedname='id')
 {
  $idwhere=is_array($idarray)?implode(',',$idarray):intval($idarray);
  $where=is_array($idarray)?"{$tbname}.{$filedname} in ({$idwhere})":" {$tbname}.{$filedname}={$idwhere}";

  return $this->query("delete from {$tbname} where {$where}",true);
 }

 function get_fields($table)
 {
  $fields=array();
  $result=$this->fetch_all("show columns from `{$table}`");
  foreach($result as $val)
  {
   $fields[]=$val['field'];
  }
  return $fields;
 }

 function get_table_status($database)
 {
  $status=array();
  $r=$this->fetch_all("show table status from `".$database."`"); /////// show table status的性质与show table类似,不过,可以提供每个表的大量信息。
  foreach($r as $v)
  {
   $status[]=$v;
  }
  return $status;
 }

 function get_one_table_status($table)
 {
  return $this->fetch_one("show table status like '$table'");
 }

 function create_fields($tbname,$fieldname,$size=0,$type='varchar') // 2010-5-14 修正一下
 {  
  if($size)
  {
   $size=strtoupper($type)=='varchar'?$size:8;
   $this->query("alter table `{$tbname}` add `$fieldname` {$type}( {$size} )  not null",true);
  }
  else $this->query("alter table `{$tbname}` add `$fieldname` mediumtext  not null",true);
  return true;
 }

 function get_tables() //获取所有表表名
 {
  $tables=array();
  $r=$this->fetch_all("show tables");
  foreach($r as $v)
  {
   foreach($v as $v_)
   {
    $tables[]=$v_;
   }
  }
  return $tables;
 }

 function create_model_table($tbname) //创建一个内容模型表(start:初始只有字段contentid int(20),用于内容表,/////////////////////// update:2010-5-20     默认加入`content` mediumtext not null,字段)
 {
  if(in_array($tbname,$this->get_tables())) return false;  ///////////////////// 当表名已经存在时,返回 false
  if($this->query("create table `{$tbname}` (
`contentid` mediumint(8) not null ,
`content` mediumtext not null,
key ( `contentid` )
) engine = myisam default charset=utf8",true))return true;   ////////////////////  成功则返回 true
  return false; //////////////失败返回 false
 }

 function create_table($tbname) //创建一个会员模型空表(初始只有字段userid int(20),用于会员表,2010-4-26)
 {
  if(in_array($tbname,$this->get_tables())) return false;
  if($this->query("create table `{$tbname}` (
`userid` mediumint(8) not null ,
key ( `userid` )
) engine = myisam default charset=utf8",true))return true;
  return false;
 }

 function escape($str) // 过滤危险字符
 {
  if(!is_array($str)) return str_replace(array('n', 'r'), array(chr(10), chr(13)),mysql_real_escape_string(preg_replace($this->search,$this->replace, $str), $this->dblink));
  foreach($str as $key=>$val) $str[$key] = $this->escape($val);
  return $str;
 }

 function filter_pass($string, $allowedtags = '', $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseo教程ver', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
 {
  if(is_array($string))
  {
   foreach($string as $key => $val) $string[$key] = $this->filter_pass($val, allowed_htmltags);
  }
  else
  {
   $string = preg_replace('/s('.implode('|', $disabledattributes).').*?([s>])/', '', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/网页特效:[^"']*/i', '/(".implode('|', $disabledattributes).")[ ]*=[ ]*["'][^"']*["']/i', '/s+/'), array('', '', ' '), stripslashes('')) . '>'", strip_tags($string, $allowedtags)));
  }
  return $string;
 }

 function drop_table($tbname)
 {
  return $this->query("drop table if exists `{$tbname}`",true);
 }

 function version()
 {
  return mysql_get_server_info($this->dblink);
 }
}

[!--infotagslink--]

相关文章

  • php正确禁用eval函数与误区介绍

    eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • PHP成员变量获取对比(类成员变量)

    下面本文章来给大家介绍在php中成员变量的一些对比了,文章举了四个例子在这例子中分别对不同成员变量进行测试与获取操作,下面一起来看看。 有如下4个代码示例,你认...2016-11-25
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • php 获取用户IP与IE信息程序

    php 获取用户IP与IE信息程序 function onlineip() { global $_SERVER; if(getenv('HTTP_CLIENT_IP')) { $onlineip = getenv('HTTP_CLIENT_IP');...2016-11-25
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • php获取一个文件夹的mtime的程序

    php获取一个文件夹的mtime的程序了,这个就是时间问题了,对于这个问题我们来看小编整理的几个例子,具体的操作例子如下所示。 php很容易获取到一个文件夹的mtime,可以...2016-11-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • php中登录后跳转回原来要访问的页面实例

    在很多网站用户先访问一个要登录的页面,但当时没有登录后来登录了,等待用户登录成功之后肯定希望返回到上次访问的页面,下面我就来给大家介绍登录后跳转回原来要访问的页...2016-11-25
  • 如何获取网站icon有哪些可行的方法

    获取网站icon,常用最简单的方法就是通过website/favicon.ico来获取,不过由于很多网站都是在页面里面设置favicon,所以此方法很多情况都不可用。 更好的办法是通过google提供的服务来实现:http://www.google.com/s2/favi...2014-06-07
  • jquery如何获取元素的滚动条高度等实现代码

    主要功能:获取浏览器显示区域(可视区域)的高度 : $(window).height(); 获取浏览器显示区域(可视区域)的宽度 :$(window).width(); 获取页面的文档高度 $(document).height(); 获取页面的文档宽度 :$(document).width();...2015-10-21
  • 金额阿拉伯数字转换为中文的自定义函数

    CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • jquery获取div距离窗口和父级dv的距离示例

    jquery中jquery.offset().top / left用于获取div距离窗口的距离,jquery.position().top / left 用于获取距离父级div的距离(必须是绝对定位的div)。 (1)先介绍jquery.offset().top / left css: 复制代码 代码如下: *{ mar...2013-10-13
  • PHP用strstr()函数阻止垃圾评论(通过判断a标记)

    strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
  • Jquery 获取指定标签的对象及属性的设置与移除

    1、先讲讲JQuery的概念,JQuery首先是由一个 America 的叫什么 John Resig的人创建的,后来又很多的JS高手也加入了这个团队。其实 JQuery是一个JavaScript的类库,这个类库集合了很多功能方法,利用类库你可以用简单的一些代...2014-05-31
  • PHP函数分享之curl方式取得数据、模拟登陆、POST数据

    废话不多说直接上代码复制代码 代码如下:/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含POST、HEADER等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header:...2014-06-07
  • php中的foreach函数的2种用法

    Foreach 函数(PHP4/PHP5)foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。...2013-09-28