两款超php分页类代码
两款超php教程分页类代码
<?php
/**
* description:超强分页类,四种分页模式,默认采用类似baidu,google的分页风格。
* 2.0增加功能:支持自定义风格,自定义样式,同时支持php4和php5,
* example:
* 模式四种分页模式:
* require_once('../libs/classes/page.class.php');
* $page=new page(array('total'=>1000,'perpage'=>20));
* echo 'mode:1<br>'.$page->show();
* echo '<hr>mode:2<br>'.$page->show(2);
* echo '<hr>mode:3<br>'.$page->show(3);
* echo '<hr>mode:4<br>'.$page->show(4);
* 开启ajax:
* $ajaxpage=new page(array('total'=>1000,'perpage'=>20,'ajax'=>'ajax_page','page_name'=>'test'));
* echo 'mode:1<br>'.$ajaxpage->show();
*/
class page
{
/**
* config ,public
*/
var $page_name="page";//page标签,用来控制url页。比如说xxx.php?page=2中的page
var $next_page='>';//下一页
var $pre_page='<';//上一页
var $first_page='first';//首页
var $last_page='last';//尾页
var $pre_bar='<<';//上一分页条
var $next_bar='>>';//下一分页条
var $format_left='[';
var $format_right=']';
var $is_ajax=false;//是否支持ajax分页模式
/**
* private
*
*/
var $pagebarnum=10;//控制记录条的个数。
var $totalpage=0;//总页数
var $ajax_action_name='';//ajax动作名
var $nowindex=1;//当前页
var $url="";//url地址头
var $offset=0;
/**
* constructor构造函数
*
* @param array $array['total'],$array['perpage'],$array['nowindex'],$array['url'],$array['ajax']
*/
function page($array)
{
if(is_array($array)){
if(!array_key_exists('total',$array))$this->error(__function__,'need a param of total');
$total=intval($array['total']);
$perpage=(array_key_exists('perpage',$array))?intval($array['perpage']):10;
$nowindex=(array_key_exists('nowindex',$array))?intval($array['nowindex']):'';
$url=(array_key_exists('url',$array))?$array['url']:'';
}else{
$total=$array;
$perpage=10;
$nowindex='';
$url='';
}
if((!is_int($total))||($total<0))$this->error(__function__,$total.' is not a positive integer!');
if((!is_int($perpage))||($perpage<=0))$this->error(__function__,$perpage.' is not a positive integer!');
if(!empty($array['page_name']))$this->set('page_name',$array['page_name']);//设置pagename
$this->_set_nowindex($nowindex);//设置当前页
$this->_set_url($url);//设置链接地址
$this->totalpage=ceil($total/$perpage);
$this->offset=($this->nowindex-1)*$this->perpage;
if(!empty($array['ajax']))$this->open_ajax($array['ajax']);//打开ajax模式
}
/**
* 设定类中指定变量名的值,如果改变量不属于这个类,将throw一个exception
*
* @param string $var
* @param string $value
*/
function set($var,$value)
{
if(in_array($var,get_object_vars($this)))
$this->$var=$value;
else {
$this->error(__function__,$var." does not belong to pb_page!");
}
}
/**
* 打开倒ajax模式
*
* @param string $action 默认ajax触发的动作。
*/
function open_ajax($action)
{
$this->is_ajax=true;
$this->ajax_action_name=$action;
}
/**
* 获取显示"下一页"的代码
*
* @param string $style
* @return string
*/
function next_page($style='')
{
if($this->nowindex<$this->totalpage){
return $this->_get_link($this->_get_url($this->nowindex+1),$this->next_page,$style);
}
return '<span class=".$style.">'.$this->next_page.'</span>';
}
/**
* 获取显示“上一页”的代码
*
* @param string $style
* @return string
*/
function pre_page($style='')
{
if($this->nowindex>1){
return $this->_get_link($this->_get_url($this->nowindex-1),$this->pre_page,$style);
}
return '<span class=".$style.">'.$this->pre_page.'</span>';
}/**
* 获取显示“首页”的代码
*
* @return string
*/
function first_page($style='')
{
if($this->nowindex==1){
return '<span class=".$style.">'.$this->first_page.'</span>';
}
return $this->_get_link($this->_get_url(1),$this->first_page,$style);
}/**
* 获取显示“尾页”的代码
*
* @return string
*/
function last_page($style='')
{
if($this->nowindex==$this->totalpage){
return '<span class=".$style.">'.$this->last_page.'</span>';
}
return $this->_get_link($this->_get_url($this->totalpage),$this->last_page,$style);
}
function nowbar($style='',$nowindex_style='')
{
$plus=ceil($this->pagebarnum/2);
if($this->pagebarnum-$plus+$this->nowindex>$this->totalpage)$plus=($this->pagebarnum-$this->totalpage+$this->nowindex);
$begin=$this->nowindex-$plus+1;
$begin=($begin>=1)?$begin:1;
$return='';
for($i=$begin;$i<$begin+$this->pagebarnum;$i++)
{
if($i<=$this->totalpage){
if($i!=$this->nowindex)
$return.=$this->_get_text($this->_get_link($this->_get_url($i),$i,$style));
else
$return.=$this->_get_text('<span class=".$nowindex_style.">'.$i.'</span>');
}else{
break;
}
$return.="n";
}
unset($begin);
return $return;
}
/**
* 获取显示跳转按钮的代码
*
* @return string
*/
function select()
{
$return='<select name="pb_page_select" >';
for($i=1;$i<=$this->totalpage;$i++)
{
if($i==$this->nowindex){
$return.='<option value="'.$i.'" selected>'.$i.'</option>';
}else{
$return.='<option value="'.$i.'">'.$i.'</option>';
}
}
unset($i);
$return.='</select>';
return $return;
}
/**
* 获取mysql教程 语句中limit需要的值
*
* @return string
*/
function offset()
{
return $this->offset;
}
/**
* 控制分页显示风格(你可以增加相应的风格)
*
* @param int $mode
* @return string
*/
function show($mode=1)
{
switch ($mode)
{
case '1':
$this->next_page='下一页';
$this->pre_page='上一页';
return $this->pre_page().$this->nowbar().$this->next_page().'第'.$this->select().'页';
break;
case '2':
$this->next_page='下一页';
$this->pre_page='上一页';
$this->first_page='首页';
$this->last_page='尾页';
return $this->first_page().$this->pre_page().'[第'.$this->nowindex.'页]'.$this->next_page().$this->last_page().'第'.$this->select().'页';
break;
case '3':
$this->next_page='下一页';
$this->pre_page='上一页';
$this->first_page='首页';
$this->last_page='尾页';
return $this->first_page().$this->pre_page().$this->next_page().$this->last_page();
break;
case '4':
$this->next_page='下一页';
$this->pre_page='上一页';
return $this->pre_page().$this->nowbar().$this->next_page();
break;
case '5':
return $this->pre_bar().$this->pre_page().$this->nowbar().$this->next_page().$this->next_bar();
break;
}
}
/*----------------private function (私有方法)-----------------------------------------------------------*/
/**
* 设置url头地址
* @param: string $url
* @return boolean
*/
function _set_url($url="")
{
if(!empty($url)){
//手动设置
$this->url=$url.((stristr($url,'?'))?'&':'?').$this->page_name."=";
}else{
//自动获取
if(empty($_server['query_string'])){
//不存在query_string时
$this->url=$_server['request_uri']."?".$this->page_name."=";
}else{
//
if(stristr($_server['query_string'],$this->page_name.'=')){
//地址存在页面参数
$this->url=str_replace($this->page_name.'='.$this->nowindex,'',$_server['request_uri']);
$last=$this->url[strlen($this->url)-1];
if($last=='?'||$last=='&'){
$this->url.=$this->page_name."=";
}else{
$this->url.='&'.$this->page_name."=";
}
}else{
//
$this->url=$_server['request_uri'].'&'.$this->page_name.'=';
}//end if
}//end if
}//end if
}
/**
* 设置当前页面
*
*/
function _set_nowindex($nowindex)
{
if(empty($nowindex)){
//系统获取
if(isset($_get[$this->page_name])){
$this->nowindex=intval($_get[$this->page_name]);
}
}else{
//手动设置
$this->nowindex=intval($nowindex);
}
}
/**
* 为指定的页面返回地址值
*
* @param int $pageno
* @return string $url
*/
function _get_url($pageno=1)
{
return $this->url.$pageno;
}
/**
* 获取分页显示文字,比如说默认情况下_get_text('<a href="">1</a>')将返回[<a href="">1</a>]
*
* @param string $str
* @return string $url
*/
function _get_text($str)
{
return $this->format_left.$str.$this->format_right;
}
/**
* 获取链接地址
*/
function _get_link($url,$text,$style=''){
$style=(empty($style))?'':'class="'.$style.'"';
if($this->is_ajax){
//如果是使用ajax模式
return '<a '.$style.' href="网页特效:'.$this->ajax_action_name.'(''.$url.'')">'.$text.'</a>';
}else{
return '<a '.$style.' href="'.$url.'">'.$text.'</a>';
}
}
/**
* 出错处理方式
*/
function error($function,$errormsg)
{
die('error in file <b>'.__file__.'</b> ,function <b>'.$function.'()</b> :'.$errormsg);
}
}
?>
代码二
/**
* 获取页码导航html
* @param $pagenum:当前页码
* @param $pagesize:每页数量
* @param $rowcount:记录总数
* @param $navurl:链接页面url
*/
function getnavhtml($pagenum,$pagesize,$rowcount,$navurl){
$pagecount = (int)($rowcount/$pagesize); //总页数
if ($rowcount % $pagesize >0){
$pagecount++;
}
if ($pagenum>$pagecount){
$pagenum = 1;
}
$firstnav = "<a href="{$navurl}page=1">首页</a> ";
$lastnav = "<a href="{$navurl}page={$pagecount}">尾页</a> ";
$prevnav="";
$nextnav="";
if ($pagenum>1){
$navpagenum = $pagenum-1;
$prevnav = "<a href="{$navurl}page={$navpagenum}">上一页</a> ";
}
if ($pagenum<$pagecount && $pagecount>1){
$navpagenum = $pagenum+1;
$nextnav = "<a href="{$navurl}page={$navpagenum}">下一页</a> ";
}
$amongnav="";//关键循环
for ($i=1;$i<=5;$i++){
$navpagenum = $pagenum+ $i-3;
if ($navpagenum>0 && $navpagenum<=$pagecount){
$navcss教程 = $navpagenum == $pagenum?" class="hover"":"";
$amongnav.="<a href="{$navurl}page={$navpagenum}" $navcss>{$navpagenum}</a> ";
}
}
return $firstnav.$prevnav.$amongnav.$nextnav.$lastnav." ".$pagenum."/".$pagecount." 共有[".$rowcount."]条数据";
}
}
下面只是简单的逻辑结构,对于正式的系统需要做具体的处理。
这里需要注意的是:加解密一定需要做安全验证。但是这个方法也不够完美,两个站点必须有相同一级域名;另外这种完全基于cookie的方式,安全性不够高
function login()
{
$info = callloginserver(); //访问登录服务器
if(!empty($info)) //登录成功了
}
//用户没有登录,则在本系统中登录并调用登录服务器接口
function login() //正常的登录
{
.......//验证用户的合法性
$_session['uid'] = $user_id;
setcookie('sign', encrypt($pass9), '', '/', 'the.com');
}
先检查用户是否在登录系统中登录
funtion sign()
{
$sign = $_cookie['sign'];
if(!empty($sign))
{
$sign = decrypt($sign);
..........///登录成功
}
}
用户没有登录,则在本系统中登录并调用登录服务器接口
function loging() //本系统登录
{
.....//登录成功
callseverlogin();//通知用户登录}
所有的站点共享一个登录系统;当用户在其中的一个站点登录成功时, 该系统调用其他站点的登录接口,完成用户在其他站点的登录,同时设置相应的登录信息;或者在用户登录时,只在该系统保存用户登录信息,当用户在其他站点登录时,必须请求该系统接口,获取用户是否登录的信息。前一种方式的缺点是:不管用户有没有使用其他站点,那些站点都需要保存用户状态;后一种方式就把所有的压力都转移到登录系统上面来。而如果要实现用户退出的统一操作,就需要站点调用登录系统的退出接口,然后登录系统接口调用其他站点的退出接口;或者设置一个标记,如果这个标记不存在则标示用户退出,此时只要把该标示清空即可,其他站点发现该标示不存在就知道用户已经退出系统。
这种处理方式需要在登录系统和个站点之间规定登录接口,和注销接口。通过这些接口,个站点可以很方便的处理用户登录或退出:
php教程 配置中的 upload_tmp_dir 这个参数进行比较,如果文件在这个目录下面,那么 move_uploaded_file 才会进行移动操作。而且这个比较是大小写敏感,/ 在windows 下面也是不一样的。而在php配置文件解析的时候,会调用一个realpath 函数,也就是是说,你在move_uploaded_file 之前,
必须对$file['tmp_name'] = realpath($file['tmp_name']); realpath 一下。
还有一种情况,大家要注意,就是 move_uploaded_file 如果配置成一个无法访问的路径,那么你不管怎么处理,move_uploaded_file 总是不能成功移动文件。
在文件上传的时候,用 move_uploaded_file 这个函数不能移动文件,而用copy 或者 rename 确是可以的。
我也一直很困惑。在文档上,说的比较模糊,就是 move_uploaded_file 这个函数,加了一步检查,检查这个文件是否是有 http post 上传的,
下面我在网上找到一个文件上传类
**文件上传类**/
class upload_file
{
/**声明**/
var $upfile_type,$upfile_size,$upfile_name,$upfile;
var $d_alt,$extention_list,$tmp,$arri;
var $datetime,$date;
var $filestr,$size,$ext,$check;
var $flash_directory,$extention,$file_path,$base_directory;
var $url; //文件上传成功后跳转路径;
function upload_file()
{
/**构造函数**/
$this->set_url("index.php"); //初始化上传成功后跳转路径;
$this->set_extention(); //初始化扩展名列表;
$this->set_size(50); //初始化上传文件kb限制;
$this->set_date(); //设置目录名称;
$this->set_datetime(); //设置文件名称前缀;
$this->set_base_directory("attachmentfile"); //初始化文件上传根目录名,可修改!;
}
/**文件类型**/
function set_file_type($upfile_type)
{
$this->upfile_type = $upfile_type; //取得文件类型;
}
/**获得文件名**/
function set_file_name($upfile_name)
{
$this->upfile_name = $upfile_name; //取得文件名称;
}
/**获得文件**/
function set_upfile($upfile)
{
$this->upfile = $upfile; //取得文件在服务端储存的临时文件名;
}
/**获得文件大小**/
function set_file_size($upfile_size)
{
$this->upfile_size = $upfile_size; //取得文件尺寸;
}
/**设置文件上传成功后跳转路径**/
function set_url($url)
{
$this->url = $url; //设置成功上传文件后的跳转路径;
}
/**获得文件扩展名**/
function get_extention()
{
$this->extention = preg_replace('/.*.(.*[^.].*)*/iu','1',$this->upfile_name); //取得文件扩展名;
}
/**设置文件名称**/
function set_datetime()
{
$this->datetime = date("ymdhis"); //按时间生成文件名;
}
/**设置目录名称**/
function set_date()
{
$this->date = date("y-m-d"); //按日期生成目录名称;
}
/**初始化允许上传文件类型**/
function set_extention()
{
$this->extention_list = "doc|xls|ppt|avi|txt|gif|jpg|jpeg|bmp|png"; //默认允许上传的扩展名称;
}
/**设置最大上传kb限制**/
function set_size($size)
{
$this->size = $size; //设置最大允许上传的文件大小;
}
/**初始化文件存储根目录**/
function set_base_directory($directory)
{
$this->base_directory = $directory; //生成文件存储根目录;
}
/**初始化文件存储子目录**/
function set_flash_directory()
{
$this->flash_directory = $this->base_directory."/".$this->date; //生成文件存储子目录;
}
/**错误处理**/
function showerror($errstr="未知错误!"){
echo "<script language=网页特效>alert('$errstr');location='javascript:history.go(-1);';</script>";
exit();
}
/**跳转**/
function go_to($str,$url)
{
echo "<script language='javascript'>alert('$str');location='$url';</script>";
exit();
}/**如果根目录没有创建则创建文件存储目录**/
function mk_base_dir()
{
if (! file_exists($this->base_directory)){ //检测根目录是否存在;
@mkdir($this->base_directory,0777); //不存在则创建;
}
}/**如果子目录没有创建则创建文件存储目录**/
function mk_dir()
{
if (! file_exists($this->flash_directory)){ //检测子目录是否存在;
@mkdir($this->flash_directory,0777); //不存在则创建;
}
}
/**以数组的形式获得分解后的允许上传的文件类型**/
function get_compare_extention()
{
$this->ext = explode("|",$this->extention_list);//以"|"来分解默认扩展名;
}
/**检测扩展名是否违规**/
function check_extention()
{
for($i=0;each($this->ext);$i++) //遍历数组;
{
if($this->ext[$i] == strtolower($this->extention)) //比较文件扩展名是否与默认允许的扩展名相符;
{
$this->check = true; //相符则标记;
break;
}
}
if(!$this->check){$this->showerror("正确的扩展名必须为".$this->extention_list."其中的一种!");}
//不符则警告
}
/**检测文件大小是否超标**/
function check_size()
{
if($this->upfile_size > round($this->size*1024)) //文件的大小是否超过了默认的尺寸;
{
$this->showerror("上传附件不得超过".$this->size."kb"); //超过则警告;
}
}/**文件完整访问路径**/
function set_file_path()
{
$this->file_path = $this->flash_directory."/".$this->datetime.".".$this->extention; //生成文件完整访问路径;
}
/**上传文件**/
function copy_file()
{
if(copy($this->upfile,$this->file_path)){ //上传文件;
print $this->go_to("文件已经成功上传!",$this->url); //上传成功;
}else {
print $this->showerror("意外错误,请重试!"); //上传失败;
}
}
/**完成保存**/
function save()
{
$this->set_flash_directory(); //初始化文件上传子目录名;
$this->get_extention(); //获得文件扩展名;
$this->get_compare_extention(); //以"|"来分解默认扩展名;
$this->check_extention(); //检测文件扩展名是否违规;
$this->check_size(); //检测文件大小是否超限;
$this->mk_base_dir(); //如果根目录不存在则创建;
$this->mk_dir(); //如果子目录不存在则创建;
$this->set_file_path(); //生成文件完整访问路径;
$this->copy_file(); //上传文件;
}
}
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>ajax php教程多文件上传代码</title>
<script>
(function(){
var d = document, w = window;/**
* get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getelementbyid(element);
return element;
}/**
* attaches event to a dom element
*/
function addevent(el, type, fn){
if (w.addeventlistener){
el.addeventlistener(type, fn, false);
} else if (w.attachevent){
var f = function(){
fn.call(el, w.event);
};
el.attachevent('on' + type, f)
}
}
/**
* creates and returns element from html chunk
*/
var toelement = function(){
var div = d.createelement('div');
return function(html){
div.innerhtml = html;
var el = div.childnodes[0];
div.removechild(el);
return el;
}
}();function hasclass(ele,cls){
return ele.classname.match(new regexp('(s|^)'+cls+'(s|$)'));
}
function addclass(ele,cls) {
if (!hasclass(ele,cls)) ele.classname += " "+cls;
}
function removeclass(ele,cls) {
var reg = new regexp('(s|^)'+cls+'(s|$)');
ele.classname=ele.classname.replace(reg,' ');
}// getoffset function copied from jquery lib (http://jquery.com/)
if (document.documentelement["getboundingclientrect"]){
// get offset using getboundingclientrect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
var getoffset = function(el){
var box = el.getboundingclientrect(),
doc = el.ownerdocument,
body = doc.body,
docelem = doc.documentelement,
// for ie
clienttop = docelem.clienttop || body.clienttop || 0,
clientleft = docelem.clientleft || body.clientleft || 0,
// in internet explorer 7 getboundingclientrect property is treated as physical,
// while others are logical. make all logical, like in ie8.
zoom = 1;
if (body.getboundingclientrect) {
var bound = body.getboundingclientrect();
zoom = (bound.right - bound.left)/body.clientwidth;
}
if (zoom > 1){
clienttop = 0;
clientleft = 0;
}
var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop,
left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft;
return {
top: top,
left: left
};
}
} else {
// get offset adding all offsets
var getoffset = function(el){
if (w.jquery){
return jquery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsettop || 0;
left += el.offsetleft || 0;
}
while (el = el.offsetparent);
return {
left: left,
top: top
};
}
}function getbox(el){
var left, right, top, bottom;
var offset = getoffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetwidth;
bottom = top + el.offsetheight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}/**
* crossbrowser mouse coordinates
*/
function getmousecoords(e){
// pagex/y is not supported in ie
// http://www.quirksmode.org/dom/w3c_css教程om.html
if (!e.pagex && e.clientx){
// in internet explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getboundingclientrect) {
var bound = body.getboundingclientrect();
zoom = (bound.right - bound.left)/body.clientwidth;
}return {
x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft,
y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop
};
}
return {
x: e.pagex,
y: e.pagey
};}
/**
* function generates unique id
*/
var getuid = function(){
var id = 0;
return function(){
return 'valumsajaxupload' + id++;
}
}();function filefrompath(file){
return file.replace(/.*(/|)/, "");
}function getext(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : '';
}/**
* cross-browser way to get xhr object
*/
var getxhr = function(){
var xhr;
return function(){
if (xhr) return xhr;
if (typeof xmlhttprequest !== 'undefined') {
xhr = new xmlhttprequest();
} else {
var v = [
"microsoft.xmlhttp",
"msxml2.xmlhttp.5.0",
"msxml2.xmlhttp.4.0",
"msxml2.xmlhttp.3.0",
"msxml2.xmlhttp.2.0"
];
for (var i=0; i < v.length; i++){
try {
xhr = new activexobject(v[i]);
break;
} catch (e){}
}
}return xhr;
}
}();// please use ajaxupload , ajax_upload will be removed in the next version
ajax_upload = ajaxupload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// variable changes to true if the button was clicked
// 3 seconds ago (requred to fix safari on mac error)
this._justclicked = false;
this._parentdialog = d.body;
if (window.jquery && jquery.ui && jquery.ui.dialog){
var parentdialog = jquery(this._button).parents('.ui-dialog');
if (parentdialog.length){
this._parentdialog = parentdialog[0];
}
}
this._settings = {
// location of the server-side upload script
action: 'upload.php',
// file upload name
name: 'userfile',
// additional data to send
data: {},
// submit file as soon as it's selected
autosubmit: true,
// the type of data that you're expecting back from the server.
// html and xml are detected automatically.
// only useful when you are using json data as a response.
// set to "json" in that case.
responsetype: false,
// location of the server-side script that fixes safari
// hanging problem returning "connection: close" header
closeconnection: '',
// class applied to button when mouse is hovered
hoverclass: 'hover',
// when user selects a file, useful with autosubmit disabled
onchange: function(file, extension){},
// callback to fire before file is uploaded
// you can return false to cancel upload
onsubmit: function(file, extension){},
// fired when file upload is completed
// warning! do not use "false" string as a response!
oncomplete: function(file, response) {}
};// merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createinput();
this._rerouteclicks();
}
// assigning methods to our class
ajaxupload.prototype = {
setdata : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes instance
destroy : function(){
if(this._input){
if(this._input.parentnode){
this._input.parentnode.removechild(this._input);
}
this._input = null;
}
},
/**
* creates invisible file input above the button
*/
_createinput : function(){
var self = this;
var input = d.createelement("input");
input.setattribute('type', 'file');
input.setattribute('name', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'width': '220px'
,'height': '30px'
,'fontsize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zindex' : 2147483583 //max zindex supported by opera 9.0-9.2x
// strange, i expected 2147483647
// doesn't work in ie :(
//,'direction' : 'ltr'
};
for (var i in styles){
input.style[i] = styles[i];
}
// make sure that element opacity exists
// (ie uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentdialog.appendchild(input);addevent(input, 'change', function(){
// get filename from input
var file = filefrompath(this.value);
if(self._settings.onchange.call(self, file, getext(file)) == false ){
return;
}
// submit form when value is changed
if (self._settings.autosubmit){
self.submit();
}
});
// fixing problem with safari
// the problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// as dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// so we should not change display to none immediately
addevent(input, 'click', function(){
self.justclicked = true;
settimeout(function(){
// we will wait 3 seconds for dialog to open
self.justclicked = false;
}, 2500);
});
this._input = input;
},
_rerouteclicks : function (){
var self = this;
// ie displays 'access denied' error when using this method
// other browsers just ignore click()
// addevent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogoffset = {top:0, left:0}, over = false;
addevent(self._button, 'mouseo教程ver', function(e){
if (!self._input || over) return;
over = true;
box = getbox(self._button);
if (self._parentdialog != d.body){
dialogoffset = getoffset(self._parentdialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addevent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeclass(self._button, self._settings.hoverclass);
input.style.display = 'none';
return;
}
var c = getmousecoords(e);if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogoffset.top + 'px';
input.style.left = c.x - dialogoffset.left + 'px';
input.style.display = 'block';
addclass(self._button, self._settings.hoverclass);
} else {
// mouse left the button
over = false;
var check = setinterval(function(){
// if input was just clicked do not hide it
// to prevent safari bug
if (self.justclicked){
return;
}
if ( !over ){
input.style.display = 'none';
}
clearinterval(check);
}, 25);
removeclass(self._button, self._settings.hoverclass);
}
});
},
/**
* creates iframe with unique name
*/
_createiframe : function(){
// unique name
// we cannot use gettime, because it sometimes return
// same value in safari :(
var id = getuid();
// remove ie6 "this page contains both secure and nonsecure items" prompt
// http://tinyurl.com/77w9wh
var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendchild(iframe);
return iframe;
},
/**
* upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = filefrompath(this._input.value);// execute user event
if (! (settings.onsubmit.call(this, file, getext(file)) == false)) {
// create new iframe for this submission
var iframe = this._createiframe();
// do not submit if user function returns false
var form = this._createform(iframe);
form.appendchild(this._input);// a pretty little hack to make uploads not hang in safari. just call this
// immediately before the upload is submitted. this does an ajax call to
// the server, which returns an empty document with the "connection: close"
// header, telling safari to close the active connection.
// http://blog.airbladesoftware.com/2007/8/17/note-to-self-prevent-uploads-hanging-in-safari
if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){
var xhr = getxhr();
// open synhronous connection
xhr.open('get', settings.closeconnection, false);
xhr.send('');
}
form.submit();
d.body.removechild(form);
form = null;
this._input = null;
// create new input
this._createinput();
var todeleteflag = false;
addevent(iframe, 'load', function(e){
if (// for safari
iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" ||
// for ff, ie
iframe.src == "javascript:'<html></html>';"){
// first time around, do not delete.
if( todeleteflag ){
// fix busy state in ff3
settimeout( function() {
d.body.removechild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document;// fixing opera 9.26
if (doc.readystate && doc.readystate != 'complete'){
// opera fires load event multiple times
// even when the dom is not ready yet
// this fix should not affect other browsers
return;
}
// fixing opera 9.64
if (doc.body && doc.body.innerhtml == "false"){
// in opera 9.64 event was fired second time
// when body.innerhtml changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.xmldocument){
// response is a xml document ie property
response = doc.xmldocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerhtml;
if (settings.responsetype && settings.responsetype.tolowercase() == 'json'){
// if the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps教程 the text in a <pre>
// tag and performs html encoding on the contents. in this case,
// we need to pull the original text content from the text node's
// nodevalue property to retrieve the unmangled content.
// note that ie6 only understands text/html
if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){
response = doc.body.firstchild.firstchild.nodevalue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.oncomplete.call(self, file, response);
// reload blank page, so that reloading main page
// does not re-submit the post. also, remember to
// delete the frame
todeleteflag = true;
// fix ie mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// doesn't work in ie6
// this._input.value = '';
d.body.removechild(this._input);
this._input = null;
// create new input
this._createinput();
}
},
/**
* creates form, that will be submitted to iframe
*/
_createform : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in ie 6/7
var form = toelement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendchild(form);
// create hidden input element for each data key
for (var prop in settings.data){
var el = d.createelement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendchild(el);
}
return form;
}
};
})();
</script>
</head><body>
<p id="errorremind"></p>
<input id="unloadpic" type="button" value="上传图片" />
<ol id="uploadedname"></ol><script type="text/javascript" src="../js/ajaxupload.js"></script>
<script type="text/javascript">
window.onload = function(){
var obtn = document.getelementbyid("unloadpic");
var oshow = document.getelementbyid("uploadedname");
var oremind = document.getelementbyid("errorremind");
new ajaxupload(obtn,{
action:"file_upload.php",
name:"upload",
onsubmit:function(file,ext){
if(ext && /^(jpg|jpeg|png|gif)$/.test(ext)){
//ext是后缀名
obtn.value = "正在上传…";
obtn.disabled = "disabled";
}else{
oremind.style.color = "#ff3300";
oremind.innerhtml = "不支持非图片格式!";
return false;
}
},
oncomplete:function(file,response){
obtn.disabled = "";
obtn.value = "再上传一张图片";
oremind.innerhtml = "";
var newchild = document.createelement("li");
newchild.innerhtml = file;
oshow.appendchild(newchild);
}
});
};
</script>
</body>
</html>
<?php #file_upload.php 2009-11-06
$file_path = '../../../uploads/';
$file_up = $file_path.basename($_files['upload']['name']);
if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){
echo 'success';
}else{
echo 'fail';
}
?>
codeigniter 具有非常容易使用的分页类。在本教程中我会做一个从数据库教程返回一组结果并分页这些结果的简单例子。我将使用最新版本的 ci。分页类并没有修改(至少我认为没有),用最新的稳定版框架总是好的
调用方法
//创建分页
$config = array();
$this->load->library('hpages');
$config['base_url'] = "channel/lists/c{$slug}/{page}";
$config['total_rows'] = intval($total);
$config['per_page'] = $pagesize;
$config['uri_segment'] = 1;
$config['num_links'] = 3;
$config['underline_uri_seg'] = 1; //下划线uri中页数所在的位置
$this->hpages->init($config);
$this->template['lists'] = $list;
$this->template['pagestr'] = $this->hpages->create_links(1);
php教程文件代码
<?php if (! defined('basepath')) exit('access denied!');
/**
* file_name : hpages.php
* 浩海网络 前台 分页类
*
* @package haohailuo
* @author by laurence.xu <haohailuo@163.com>
* @copyright copyright (c) 2010, haohailuo, inc.
* @link http://www.haohailuo.com
* @since version 1.0 $id$
* @version wed dec 08 12:21:17 cst 2010
* @filesource
*/
class hpages {var $base_url = ''; //基本链接地址
var $total_rows = ''; //数据总数
var $per_page = 10; //每页条数
var $num_links = 2; //要显示的左右链接的个数
var $cur_page = 1; //当前页数
var $first_link = '‹ first'; //首页字符
var $next_link = '>'; //下一页的字符
var $prev_link = '<'; //上一页的字符
var $last_link = 'last ›'; //末页的字符
var $uri_segment = 3; //分页数所在的uri片段位置
var $full_tag_open = ''; //分页区域开始的html标签
var $full_tag_close = ''; //分页区域结束的后html标签
var $first_tag_open = ''; //首页开始的html标签
var $first_tag_close = ' '; //首页结束的html标签
var $last_tag_open = ' '; //末页开始的html标签
var $last_tag_close = ''; //末页结束的html标签
var $cur_tag_open = ' <b>';//当前页开始的...
var $cur_tag_close = '</b>'; //当前页结束的...
var $next_tag_open = ' '; //下一页开始的.....
var $next_tag_close = ' '; //下一页结束的.....
var $prev_tag_open = ' '; //上一页开始的.....
var $prev_tag_close = ''; //上一页结束的.....
var $num_tag_open = ' '; //“数字”链接的打开标签。
var $num_tag_close = ''; //“数字”链接的结束标签。
var $page_query_string = false;
var $query_string_segment = 'per_page';
var $page_mode = 'default'; //default for add page at the end? if include {page}, will replace it for current page.
var $underline_uri_seg = -1; //存在下划线时,页码所在数组下标位置
var $custom_cur_page = 0; //自定义当前页码,存在此值是,系统将不自动判断当前页数,默认不启用
function __construct() {
$this->hpages();
}
/**
* constructor
*
* @access public
*/
function hpages() {
if (file_exists(apppath.'config/pagination.php')) {
require_once(apppath.'config/pagination.php');
foreach ($config as $key=>$val) {
$this->{$key} = $val;
}
}
log_message('debug', "hpages class initialized");
}
/**
* 初始化参数
*
* @see init()
* @author laurence.xu <haohailuo@163.com>
* @version wed dec 08 12:26:07 cst 2010
* @param <array> $params 待初始化的参数
*/
function init($params = array()) {
if (count($params) > 0) {
foreach ($params as $key => $val) {
if (isset($this->$key)) {
$this->$key = $val;
}
}
}
}
/**
* 创建分页链接
*
* @see create_links()
* @author laurence.xu <haohailuo@163.com>
* @version wed dec 08 15:02:27 cst 2010
* @param <boolean> $show_info 是否显示总条数等信息
* @return <string> $output
*/
function create_links($show_info = false, $top_info = false) {
//如果没有记录或者每页条数为0,则返回空
if ($this->total_rows == 0 || $this->per_page == 0) {
return '';
}//计算总页数
$num_pages = ceil($this->total_rows / $this->per_page);//只有一页,返回空
if ($num_pages == 1 && !$show_info) {
return '';
}
$ci =& get_instance();//获取当前页编号
if ($ci->config->item('enable_query_strings') === true || $this->page_query_string === true) {
if ($ci->input->get($this->query_string_segment) != 0) {
$this->cur_page = $ci->input->get($this->query_string_segment);// prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
} else {
if (intval($this->custom_cur_page) > 0) {
$this->cur_page = (int) $this->custom_cur_page;
}else{
$uri_segment = $ci->uri->segment($this->uri_segment, 0);
if ( !empty($uri_segment) ) {
$this->cur_page = $uri_segment;
//如果有下划线
if ($this->underline_uri_seg >= 0) {
if (strpos($this->cur_page, '-') !== false) {
$arr = explode('-', $this->cur_page);
}else {
$arr = explode('_', $this->cur_page);
}
$this->cur_page = $arr[$this->underline_uri_seg];
unset($arr);
}
// prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
}
//echo $this->cur_page;exit;
//左右显示的页码个数
$this->num_links = (int)$this->num_links;if ($this->num_links < 1) {
show_error('your number of links must be a positive number.');
}if ( ! is_numeric($this->cur_page) || $this->cur_page < 1) {
$this->cur_page = 1;
}
//如果当前页数大于总页数,则赋值给当前页数最大值
if ($this->cur_page > $num_pages) {
$this->cur_page = $num_pages;
}$uri_page_number = $this->cur_page;
if ($ci->config->item('enable_query_strings') === true || $this->page_query_string === true) {
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
} else {
$this->base_url = rtrim($this->base_url, '/') .'/';
}
if (strpos($this->base_url, "{page}") !== false) {
$this->page_mode = 'replace';
}
$output = $top_output = '';
//数据总量信息
if ($show_info) {
$output = " 共<b>".$this->total_rows ."</b>条记录 <span style='color:#ff0000;font-weight:bold'>{$this->cur_page}</span>/<b>".$num_pages."</b>页 每页<b>{$this->per_page}</b>条 ";
}
//数据信息,显示在上面,以供提醒
if ($top_info) {
$top_output = " 共 <b>".$this->total_rows ."</b> 条记录 第<span style='color:#ff0000;font-weight:bold'>{$this->cur_page}</span>页/共<b>".$num_pages."</b>页 ";
}
//判断是否要显示首页
if ($this->cur_page > $this->num_links+1) {
$output .= $this->first_tag_open.'<a href="'.$this->makelink().'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
//显示上一页
if ($this->cur_page != 1) {
$j = $this->cur_page - 1;
if ($j == 0) $j = '';
$output .= $this->prev_tag_open.'<a href="'.$this->makelink($j).'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
//显示中间页
for ($i=1; $i <= $num_pages; $i++){
if ($i < $this->cur_page-$this->num_links || $i > $this->cur_page+$this->num_links) {
continue;
}
//显示中间页数
if($this->cur_page == $i){
$output .= $this->cur_tag_open.$i.$this->cur_tag_close; //当前页
}else {
$output .= $this->num_tag_open.'<a href="'.$this->makelink($i).'">'.$i.'</a>'.$this->num_tag_close;
}
}
//显示下一页
if ($this->cur_page < $num_pages) {
$k = $this->cur_page + 1;
$output .= $this->next_tag_open.'<a href="'.$this->makelink($k).'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
//显示尾页
if (($this->cur_page + $this->num_links) < $num_pages) {
$output .= $this->last_tag_open.'<a href="'.$this->makelink($num_pages).'">'.$this->last_link.'</a>'.$this->last_tag_close;
}$output = preg_replace("#([^:])//+#", "1/", $output);
// add the wrapper html if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;if ($top_info) {
return array($output, $top_output);
}else {
return $output;
}
}
/**
* 创建链接url地址
*
* @param <string> $str
* @return <string>
*/
function makelink($str = '') {
if($this->page_mode == 'default') {
return $this->_forsearch($this->base_url.$str);
} else {
$url = $this->base_url;
if ($str == 1) {
$url = str_replace('/{page}', '', $this->base_url);
}
$url = str_replace("{page}", $str, $url);
return $this->_forsearch($url);
}
}
/**
* 处理url地址
*
* @see _forsearch()
* @author laurence.xu <haohailuo@163.com>
* @version wed dec 08 14:33:58 cst 2010
* @param <string> $string pinfo
* @return <string>
*/
function _forsearch($string) {
$length = strlen($string) - 1;
if($string{$length} == '/') {
$string = rtrim($string, '/');
}
return site_url($string);
return $string;
}
}// end pagination class
/* end of file hpages.php */
/* location: ./system/libraries/hpages.php */
相关文章
- 我们这里介绍php与KindEditor编辑器使用时如何利用KindEditor编辑器的分页功能实现文章内容分页,KindEditor编辑器在我们点击分页时会插入代码,我们只要以它为分切符,就...2016-11-25
- 最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
- 有一种方法,可以不打开网站而直接查看到这个网站的源代码.. 这样可以有效地防止误入恶意网站... 在浏览器地址栏输入: view-source:http://...2016-09-20
- <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
- 本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
- 本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
- 本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
- 本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
- php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
- php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p> </p> <p> </p> <form name="form1...2016-11-25
- 公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
- 本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
- 其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
- 一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
- 微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
- Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.这篇文章主要介绍了vue.js 表格分页ajax 异步加载数据的相关资料,需要的朋友可以参考下...2016-10-20
- 本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
- 小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
php导出csv格式数据并将数字转换成文本的思路以及代码分享
php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07- 本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13