设为首页 收藏本站
查看: 1251|回复: 0

[经验分享] php 学习整理

[复制链接]

尚未签到

发表于 2015-8-23 17:50:17 | 显示全部楼层 |阅读模式
  1、页面提交信息过虑方法



function adds($string, $force = 0)
{
!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
if(!MAGIC_QUOTES_GPC || $force) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = adds($val, $force);
}
} else {
$string = addslashes($string);
}
}
$words = array('SELECT ', 'INSERT ', 'UPDATE ', 'DELETE ', 'CREATE ', 'DROP ', 'RELOAD ', 'SHUTDOWN', 'PROCESS',  'REFERENCES', 'ALTER', 'SHOW DATABASES', 'CREATE TEMPORARY TABLES', 'LOCK TABLES', 'REPLICATION SLAVE', 'REPLICATION CLIENT', 'CREATE VIEW', 'SHOW VIEW', 'CREATE ROUTINE', 'ALTER ROUTINE', 'EXECUTE');
foreach($words as $wd)
{
if(stristr($string,$wd))
{
exit('Access Denied');
}
}
$search = array('/union(\s*(\/\*.*\*\/)?\s*)+select/i', '/load_file(\s*(\/\*.*\*\/)?\s*)+\(/i', '/into(\s*(\/\*.*\*\/)?\s*)+outfile/i','/;/','/%/');
$replace = array('union   select', 'load_file   (', 'into   outfile','\;','\%');
return preg_replace($search,$replace,$string);
}
  

2、跨站脚本的过滤RemoveXss函数  



function RemoveXSS($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <java\0script>
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(&#0{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
  3、php正则匹配中文



preg_match ( '/^[\x{0391}-\x{FFE5}]{2,6}$/u', $realname )
   4、php实现身份证号与姓名验证



/*--------------- 身份证校验接口 ---------------*/
define('idcard_interface','http://ngs.nciic.net.cn/nciic_ws/services/NciicServices?wsdl');
define('idcard_inLicense','?v>xB::^9*3;V]-T_=CZ)FSKJ3?c;t?g3o?h?o?[7_M2K7^X>#TJ/DSB$t?oUlUe@s?o?z-;S$?vE/JvBxa3PpBkM.?x?vQbIyFvXaCaa _tAg?x?vNn[;Fh`3<c?s1/b)4v;v?v<;NnGh`8An?x6a\na8UiTj3f1n3sc_:c>h?v?jVhEfIzQq?x?vCt[;^eHd?x3Q9U1S3$JJ%&P2P:9a?f?hd)?.?v*nOqYkRuRw;n?vSv[yNo^fEl\;NiUk2dMv?g5b>h&e?g?va{@jNhVnFqNtDs\g`38m$rKcLi?j?x?v`}[g^f^uNiIz\l`5_j?x?vSzJh_fcN[lBx[pUi@gEvG.?x8bWk^/GgVl8m&q?h?a?s*w:qJd@eGga4?x?v8eWbZ[cXLyZ;EmPqXkYeEvAg?x<z?j^lb0LhL/F.AlUj2d');
function check_idcard_from_interface($card,$name,$flag =0)
{
//检查身份证接口,$flag 决定返回结果类型
// SoapClient是php5的扩展,实现简单对象访问协议,
// 简单对象访问协议(SOAP)是一种轻量的、简单的、基于 XML 的协议,它被设计成在 WEB 上交换结构化的和固化的信息。
// PHP5中的这个SOAP扩展目的是为了实现PHP对Web services的支持。与其它实现PHP对Web services的支持的方法不同,
// SOAP扩展是用C写的,因此它比其它方法具有速度优势。
$client = new SoapClient( idcard_interface, array('trace' => 1 ));
$params['inLicense'] = idcard_inLicense;
$params['inConditions'] = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><ROWS><INFO><SBM>武神世纪</SBM></INFO><ROW><GMSFHM>公民身份号码</GMSFHM><XM>姓名</XM></ROW><ROW FSD=\"**\" YWLX=\"**\" > <GMSFHM>{$card}</GMSFHM><XM>{$name}</XM></ROW></ROWS>";
$result = -1;
try{
$something =  $client->nciicCheck($params);
$result = $something->out;
if( strstr($result,'<result_xm>一致</result_xm>') ){
$result = 2; //身份证和姓名匹配
}elseif( strstr($result,'<result_gmsfhm>一致</result_gmsfhm>') ){
$result = -3;//身份证合法
}else{
$result = -4;//身份证不合法
    }
}catch (Exception $e){
$result = -1;
}
if( $flag==1 ){
if($result == 2){
$result =1;
}elseif($result != -1){
$result =0;
}
}
return $result;
}

$card = "验证的身份证号";
$name = "验证的姓名";
$checkResult = check_idcard_from_interface($card,$name);
echo $checkResult;
   5、php写系统日志



$facility = LOG_LOCAL5;
$priority = LOG_USER|LOG_INFO;
$ident = "testsyslog";
$option = LOG_PID;
openlog($ident,$option,$facility);
syslog($priority,"syslog test message generated in program  \n");
closelog();
  调用的是操作系统的日志函数,详细可参考:http://www.iyunv.com/wangkangluo1/archive/2012/05/30/2526011.html
  6、产生随机码



//产生随机码
function CreateRandomCode() {
$code = time () * 3 * mt_rand ( 1000, 9999 );
return sha1 ( $code );
}
   7、校验请求来源



/**
* @name CheckRef 校验来源
* @param string $str
* @return boolean
*/
function CheckRef()
{
if(!empty($_SERVER['HTTP_REFERER'])){
$host = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'];
$url = parse_url($_SERVER['HTTP_REFERER']);
if( $url['scheme'].'://'.$url['host'] == $host)
return TRUE;
}
return FALSE;
}
  8、截取中文字符串方法
  



function cutstr($string, $length, $dot = ' ...', $charset = 'utf-8'){
if(strlen($string) <= $length) {
return $string;
}
$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
$strcut = '';
if(strtolower($charset) == 'utf-8') {
$n = $tn = $noc = 0;
while($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
} else {
for($i = 0; $i < $length; $i++) {
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
//return $strcut.$dot;
return $strcut;
}
  9、加密码解密码函数,可用以cookie加密



define('_PSW_ENCODE','aaaaaa');//定义一个用来加密码的用的串
function encode($string) {
$iv = mcrypt_create_iv ( mcrypt_get_iv_size ( MCRYPT_3DES, MCRYPT_MODE_ECB ), MCRYPT_RAND );
$encode = base64_encode ( @mcrypt_encrypt ( MCRYPT_3DES, _PSW_ENCODE, $string, MCRYPT_MODE_ECB, $iv ) );
return $encode;
}
function decode($string) {
$decode = @mcrypt_decrypt ( MCRYPT_3DES, _PSW_ENCODE, base64_decode ( $string ), MCRYPT_MODE_ECB );
return $decode;
}
  10、获取ip,ip转成整型,整型转成ip
  



//获取ip
function getRemoteAddr() {
if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" )) {
$ip = getenv ( "HTTP_CLIENT_IP" );
} else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" )) {
$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
} else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" )) {
$ip = getenv ( "REMOTE_ADDR" );
} else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" )) {
$ip = $_SERVER ['REMOTE_ADDR'];
} else {
$ip = '';
}
return $ip;
}
//整型转ip
function longtoip( $ip )
{
return long2ip( $ip + 2147483648 );
}
//ip转整型,有可能为负值
function iptolong( $ip )
{
return sprintf( "%u", ip2long($ip) ) - 2147483648;
}
  
   11、输出分页方法
  



1 /*
2 currentPage:当前页
3 totalPage:总页数
4 url:分页连接
5 count:数据总条数   
6 halfPer:分布标签中当前页的两边显示多少项。
7 */
8 function adminpage($currentPage,$totalPage,$url,$count=0,$halfPer=5)
9 {
10         $total=$totalPage;
11         $url = $url.'&page';
12         $currentPage=($currentPage<1)?1:$currentPage;
13         $currentPage=($currentPage>$totalPage)?$totalPage:$currentPage;
14         $re="记录总数:$count 条 ";
15         $re .= ( $currentPage > 1 )
16             ? " <a href=\"$url=1\">首页</a> \n <a href=\"$url=".($currentPage-1)."\">上一页</a> \n"
17             : " 首页 \n";
18         
19         for ( $i = $currentPage - $halfPer,$i >= 1 || $i = 1 ,$j = $currentPage + $halfPer, $j < $totalPage || $j = $totalPage;$i <= $j ;$i++ )
20         {
21             $re .= ($i == $currentPage)? " <b class=currentPage> $i </b> \n" : " <a href=\"$url=$i\"> $i </a> \n";
22         }
23         $re .= ( $currentPage < $total ) ? " <a href=\"$url=" . ( $currentPage + 1 ) . "\">下一页</a>\n<a href=\"$url=" . ( $total )."\">尾页</a>\n" : " 尾页 \n";
24         return $re;
25 }
  
  
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-103156-1-1.html 上篇帖子: PHP配置文件详解php.ini 下篇帖子: php随机输出名人名言
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表