当前位置: 编程技术>php
本页文章导读:
▪php ajax 静态分页过程形式
代码如下: js 端 及判断 <script language='javascript' > $(function(){ //var url=$(this)[0].location.href; //alert(url); goPageFirst(); $('#selpage').bind('change',goPage); }); //返回当前页数 function getNowPage() { return parseInt.........
▪php中防止伪造跨站请求的小招式
伪造跨站请求介绍 伪造跨站请求比较难以防范,而且危害巨大,攻击者可以通过这种方式恶作剧,发spam信息,删除数据等等。这种攻击常见的表现形式有: 伪造链接,引诱用户点.........
▪10个实用的PHP代码片段
关键词高亮 代码如下: function highlight($sString, $aWords) { if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) { return false; } $sWords = implode ('|', $aWords); return preg_replace ('@\b('.$sWords.')\b@si', '<strong.........
[1]php ajax 静态分页过程形式
来源: 互联网 发布时间: 2013-11-30
代码如下:
js 端 及判断
<script language='javascript' >
$(function(){
//var url=$(this)[0].location.href;
//alert(url);
goPageFirst();
$('#selpage').bind('change',goPage);
});
//返回当前页数
function getNowPage()
{
return parseInt($('#nowPage').html());
}
//返回每页显示的条数
function getPer()
{
return $('#perPage').val();
}
//返回总记录数
function getTotal()
{
return parseInt($('#total').html());
}
//返回总页数
function getAllPage()
{
return parseInt($('#allpage').html());
}
//组合字符串参数
function getData(act)
{
var target=1;
var now=getNowPage()+1;
var per=getPer();
var sum=getTotal();
var allpage=getAllPage();
switch(act)
{
case 'first':
target=1;
break;
case 'prev':
target=now>1?now-1:1;
break;
case 'next':
target=now+1>allpage?now:1;
break;
case 'last':
target=allpage>0?allpage:1;
break;
case 'constans':
target=$('#selpage').val()>0?$('#selpage').val():1;
default :
target=1;
}
var data="check="+act+"&nowpage="+now+"&perpage="+per+'&target='+target;
alert(data);
return data;
}
//执行第一页
function goPageFirst()
{
var param=getData('first');
http_post(param);
}
//执行上一页
function goPagePrev()
{
var param=getData('prev');
http_post(param);
}
//执行下一页
function goPageNext()
{
var param=getData('next');
http_post(param);
}
//执行最后页
function goPageLast()
{
var param=getData('last');
http_post(param);
}
//选中到指定页面
function goPage()
{
var param=getData('constans');
http_post(param);
}
//post 请求数据加载
function http_post(db)
{
$.post('./mysql.php',db,function(data){
responseAjax(data);
},'text');
}
//返回数据的调处理
function responseAjax(msg)
{
//alert(msg);
//alert(msg.content);
//$('#listDiv').html(msg.content);
$('#listDiv').html(msg);
}
server端 判断及实现
//@autor 499188204@qq.com
mb_internal_encoding('gb2312');
$con=mysql_connect("127.0.0.1","root","12345678") or die("连接失败");
$m=mysql_select_db("ec",$con);
$sql = 'SELECT `attr_id`,`cat_id`,`attr_name`
FROM `ecs_attribute` ';
$rs = mysql_query($sql );
$count = mysql_num_rows($rs); //返回记录总数
//echo $count; //总记录数
//每页的记录数 10
//求总页数 ceil($count/10)
//echo '<hr >';
if(!isset($_POST['check']))
{
$set['id']=0;
die('no access please!');
}
if(isset($_POST['perpage']) && $_POST['perpage']>0 )
{
$per=$_POST['perpage'];
}
else
{
$per=15;
}
$page = ceil($count/$per);
//echo $page;
if(!isset($_POST['nowpage']))
{
$nowPage=1;
}
else
{
$nowPage = $_POST['nowpage'];
}
$start = ($nowPage-1)*$per+1;
$sql = 'select `attr_id`,`cat_id`,`attr_name` from `ecs_attribute` limit '.$start.','. $per;
//$sql = 'select `attr_id`,`cat_id`,`attr_name` from `ecs_attribute` limit 10 offset 20';
$rs = mysql_query($sql );
$str = "<table id='content'>
<tr><th>属性编号</th><th>类型编号</th><th>属性名字</th></tr>";
while($row = mysql_fetch_assoc($rs)){
$str .='<tr><td>'.$row['attr_id'].'</td><td>'.$row['cat_id'].'</td><td>'.$row['attr_name'].'</td><tr>';
}
$str.="</table>
<table id='page_list'>
<tr><td><div><span>总计<span id='total'>".$count."</span>个记录分为<span id='allpage'>".$page."</span>页当前第<span id='nowPage'>".$nowPage."</span>页,每页<input type='text' id='perPage' value='".$per."'/> |
<a href='javascript:void(0)' onclick='goPageFirst()'>第一页</a>
<a href='javascript:void(0)' onclick='goPagePrev()'>上一页</a>
<a href='javascript:void(0)' onclick='goPageFirst()'>下一页</a>
<a href='javascript:void(0)' onclick='goPageFirst()'>最末页 </a>
<select id='selpage' >";
for($i=1;$i <=$page;$i++)
{
if($nowPage==$i)
{
$str .= "<option selected >".$i."</option>";
}
else
{
$str .= "<option >".$i."</option>";
}
}
$str .="</select>
</span></div></td></tr>
</table>";
echo mb_convert_encoding($str,'UTF-8','gb2312');
//$set['content']=$str;
//echo json_encode($set);
?>
[2]php中防止伪造跨站请求的小招式
来源: 互联网 发布时间: 2013-11-30
伪造跨站请求介绍
伪造跨站请求比较难以防范,而且危害巨大,攻击者可以通过这种方式恶作剧,发spam信息,删除数据等等。这种攻击常见的表现形式有:
伪造链接,引诱用户点击,或是让用户在不知情的情况下访问
伪造表单,引诱用户提交。表单可以是隐藏的,用图片或链接的形式伪装。
比较常见而且也很廉价的防范手段是在所有可能涉及用户写操作的表单中加入一个随机且变换频繁的字符串,然后在处理表单的时候对这个字符串进行检查。这个随机字符串如果和当前用户身份相关联的话,那么攻击者伪造请求会比较麻烦。
yahoo对付伪造跨站请求的办法是在表单里加入一个叫.crumb的随机串;而facebook也有类似的解决办法,它的表单里常常会有post_form_id和fb_dtsg。
随机串代码实现
咱们按照这个思路,山寨一个crumb的实现,代码如下:
<?php
class Crumb {
CONST SALT = "your-secret-salt";
static $ttl = 7200;
static public function challenge($data) {
return hash_hmac('md5', $data, self::SALT);
}
static public function issueCrumb($uid, $action = -1) {
$i = ceil(time() / self::$ttl);
return substr(self::challenge($i . $action . $uid), -12, 10);
}
static public function verifyCrumb($uid, $crumb, $action = -1) {
$i = ceil(time() / self::$ttl);
if(substr(self::challenge($i . $action . $uid), -12, 10) == $crumb ||
substr(self::challenge(($i - 1) . $action . $uid), -12, 10) == $crumb)
return true;
return false;
}
}
代码中的$uid表示用户唯一标识,而$ttl表示这个随机串的有效时间。
应用示例
构造表单
在表单中插入一个隐藏的随机串crumb
<form method="post" action="/blog_article/demo.html">
<input type="hidden" name="crumb" value="<?php echo Crumb::issueCrumb($uid)?>">
<input type="text" name="content">
<input type="submit">
</form>
处理表单 demo.php
对crumb进行检查
<?php
if(Crumb::verifyCrumb($uid, $_POST['crumb'])) {
//按照正常流程处理表单
} else {
//crumb校验失败,错误提示流程
}
?>
伪造跨站请求比较难以防范,而且危害巨大,攻击者可以通过这种方式恶作剧,发spam信息,删除数据等等。这种攻击常见的表现形式有:
伪造链接,引诱用户点击,或是让用户在不知情的情况下访问
伪造表单,引诱用户提交。表单可以是隐藏的,用图片或链接的形式伪装。
比较常见而且也很廉价的防范手段是在所有可能涉及用户写操作的表单中加入一个随机且变换频繁的字符串,然后在处理表单的时候对这个字符串进行检查。这个随机字符串如果和当前用户身份相关联的话,那么攻击者伪造请求会比较麻烦。
yahoo对付伪造跨站请求的办法是在表单里加入一个叫.crumb的随机串;而facebook也有类似的解决办法,它的表单里常常会有post_form_id和fb_dtsg。
随机串代码实现
咱们按照这个思路,山寨一个crumb的实现,代码如下:
代码如下:
<?php
class Crumb {
CONST SALT = "your-secret-salt";
static $ttl = 7200;
static public function challenge($data) {
return hash_hmac('md5', $data, self::SALT);
}
static public function issueCrumb($uid, $action = -1) {
$i = ceil(time() / self::$ttl);
return substr(self::challenge($i . $action . $uid), -12, 10);
}
static public function verifyCrumb($uid, $crumb, $action = -1) {
$i = ceil(time() / self::$ttl);
if(substr(self::challenge($i . $action . $uid), -12, 10) == $crumb ||
substr(self::challenge(($i - 1) . $action . $uid), -12, 10) == $crumb)
return true;
return false;
}
}
代码中的$uid表示用户唯一标识,而$ttl表示这个随机串的有效时间。
应用示例
构造表单
在表单中插入一个隐藏的随机串crumb
代码如下:
<form method="post" action="/blog_article/demo.html">
<input type="hidden" name="crumb" value="<?php echo Crumb::issueCrumb($uid)?>">
<input type="text" name="content">
<input type="submit">
</form>
处理表单 demo.php
对crumb进行检查
代码如下:
<?php
if(Crumb::verifyCrumb($uid, $_POST['crumb'])) {
//按照正常流程处理表单
} else {
//crumb校验失败,错误提示流程
}
?>
[3]10个实用的PHP代码片段
来源: 互联网 发布时间: 2013-11-30
关键词高亮
function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
return false;
}
$sWords = implode ('|', $aWords);
return preg_replace ('@\b('.$sWords.')\b@si', '<strong >$1</strong>', $sString);
}
获取你的Feedburner的用户
function get_average_readers($feed_id,$interval = 7){
$today = date('Y-m-d', strtotime("now"));
$ago = date('Y-m-d', strtotime("-".$interval." days"));
$feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $feed_url);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
$nb = 0;
foreach($xml->feed->children() as $circ){
$nb += $circ['circulation'];
}
return round($nb/$interval);
}
自动生成密码
function generatePassword($length=9, $strength=0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8 ) {
$vowels .= '@#$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
压缩多个CSS文件
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');
ob_end_flush();
获取短网址
function getTinyUrl(/blog_article/$url/index.html) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}
根据生日计算年龄
function age($date){
$year_diff = '';
$time = strtotime($date);
if(FALSE === $time){
return '';
}
$date = date('Y-m-d', $time);
list($year,$month,$day) = explode("-",$date);
$year_diff = date("Y") – $year;
$month_diff = date("m") – $month;
$day_diff = date("d") – $day;
if ($day_diff < 0 || $month_diff < 0) $year_diff–;
return $year_diff;
}
计算执行时间
//Create a variable for start time
$time_start = microtime(true);
// Place your PHP/HTML/JavaScript/CSS/Etc. Here
//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;
echo 'Script took '.$time.' seconds to execute';
PHP的维护模式
function maintenance($mode = FALSE){
if($mode){
if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
header("Location: http://example.com/maintenance.php");
exit;
}
}else{
if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
header("Location: http://example.com/");
exit;
}
}
}
阻止CSS样式被缓存
<link href="/stylesheet.css" rel="stylesheet" type="text/css" /&glt;
为数字增加 st\nd\rd 等
function make_ranked($rank) {
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';
if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';
return $rank.$ext;
}
代码如下:
function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
return false;
}
$sWords = implode ('|', $aWords);
return preg_replace ('@\b('.$sWords.')\b@si', '<strong >$1</strong>', $sString);
}
获取你的Feedburner的用户
代码如下:
function get_average_readers($feed_id,$interval = 7){
$today = date('Y-m-d', strtotime("now"));
$ago = date('Y-m-d', strtotime("-".$interval." days"));
$feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $feed_url);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
$nb = 0;
foreach($xml->feed->children() as $circ){
$nb += $circ['circulation'];
}
return round($nb/$interval);
}
自动生成密码
代码如下:
function generatePassword($length=9, $strength=0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8 ) {
$vowels .= '@#$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
压缩多个CSS文件
代码如下:
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');
ob_end_flush();
获取短网址
代码如下:
function getTinyUrl(/blog_article/$url/index.html) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}
根据生日计算年龄
代码如下:
function age($date){
$year_diff = '';
$time = strtotime($date);
if(FALSE === $time){
return '';
}
$date = date('Y-m-d', $time);
list($year,$month,$day) = explode("-",$date);
$year_diff = date("Y") – $year;
$month_diff = date("m") – $month;
$day_diff = date("d") – $day;
if ($day_diff < 0 || $month_diff < 0) $year_diff–;
return $year_diff;
}
计算执行时间
代码如下:
//Create a variable for start time
$time_start = microtime(true);
// Place your PHP/HTML/JavaScript/CSS/Etc. Here
//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;
echo 'Script took '.$time.' seconds to execute';
PHP的维护模式
代码如下:
function maintenance($mode = FALSE){
if($mode){
if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
header("Location: http://example.com/maintenance.php");
exit;
}
}else{
if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
header("Location: http://example.com/");
exit;
}
}
}
阻止CSS样式被缓存
代码如下:
<link href="/stylesheet.css" rel="stylesheet" type="text/css" /&glt;
为数字增加 st\nd\rd 等
代码如下:
function make_ranked($rank) {
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';
if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';
return $rank.$ext;
}
最新技术文章: