PHP 一个完整的分页类(附源码)

 更新时间:2016年11月25日 17:28  点击:3131
在php中要实现分页比起asp中要简单很多了,我们核心就是直接获取当前页面然后判断每页多少再到数据库中利用limit就可以实现分页查询了,下面我来详细介绍分页类实现程序。


如果是ajax调用:

//$total,总数(int);$size,每页显示数量(int);$page,当前页(int),$url,链接(string);ajax,js函数名;

$page = new Page(array('total'=>$total,'perpage'=>$size,'nowindex'=>$page,'url' => $url,'ajax' => 'videoGoToPage'));

//变量$page_html为分页的html,参数4是分页的显示样式是第四种
$page_html = $page->show(4);
//然后在页面中加入jQuery包和js代码:

function videoGoToPage(u)
{
if(!u)
{
return false;
}
$.ajax({
type: “POST”,
url: “” + u,
data: “”,
success: function(msg){
//alert( “Data Saved: ” + msg );
$(“#tonglei”).html(msg);
}
});
}

如果不是ajax调用:

//直接去掉数组中'ajax'这项就可以了

$page = new Page(array('total'=>$total,'perpage'=>$size,'nowindex'=>$page,'url' => $url));

$page_html = $page->show(4);

说明:对于url,因为我用的是伪静态,比如我的页面链接是  search-1.html 表示第一页,search-2.html为第二页,那么我的$url变量

就应该写成   $url = 'search-';

分页类会自动补全后面的   “页数 .html”,这里可以根据自己的需要修改分页类。

下面把page.class.php分享给大家

 代码如下 复制代码

<?php
/**
 * filename: ext_page.class.php
 * @package:phpbean
 * @author :feifengxlq<feifengxlq#gmail.com>
 * @copyright :Copyright 2006 feifengxlq
 * @license:version 2.0
 * @create:2006-5-31
 * @modify:2006-6-1
 * @modify:feifengxlq 2006-11-4
 * description:超强分页类,四种分页模式,默认采用类似baidu,google的分页风格。
 * 2.0增加功能:支持自定义风格,自定义样式,同时支持PHP4和PHP5,
 * to see detail,please visit http://www.111cn.net * 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();
   采用继承自定义分页显示模式:
   demo:[url=http://www.phpobject.net/blog]http://www.phpobject.net/blog[/url]
 */
class Page
{
 /**
  * config ,public
  */
 var $page_name="p";//page标签,用来控制url页。比如说xxx.php?PB_page=2中的PB_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)*$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='c')
 {
  $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='&gt;';
    $this->pre_page='&lt;';
    $this->first_page='&lt;&lt;';
    $this->last_page='&gt;&gt;';
    return $this->first_page().$this->pre_page().$this->nowbar().$this->next_page().$this->last_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;
  }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 . '.html';
 }

 /**
  * 获取分页显示文字,比如说默认情况下_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="javascript:'.$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);
 }
}
?>

php分页类源码下载包:http://file.111cn.net/download/2013/06/08/pageClass.rar

在很多网站用户先访问一个要登录的页面,但当时没有登录后来登录了,等待用户登录成功之后肯定希望返回到上次访问的页面,下面我就来给大家介绍登录后跳转回原来要访问的页面实例

最简单的办法就是直接使用php $_SERVER['HTTP_REFERER']


如果我在A.php页面要登录


现在跳到B.php页面,我们只要在b.php中加如下代码

 代码如下 复制代码

$url = $_SERVER['HTTP_REFERER'];
header("location:$url");

但是上面的办法会有很多不足,如带参数等等,但在IE浏览器下的话,假如你是通过js的location来跳转的话,那这个值是获取不到的。

 下面我做一个全面点的。


首先创建一个方法判断是否登录,如果没登录则

 代码如下 复制代码

protected function checkLogin() {
       if (没有登录){          
       $thisurl = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];//当前URL
       $thisurl = urlencode($thisurl);//这里要注意需要把获取到的url转码,不然后面不好传递URL
           redirect("http://".$_SERVER["HTTP_HOST"]."/cityosweb/default.php/Index/login?url=".$thisurl);           
       }
   }

然后在需要登录的才能反问的页面调用这个方法:

 代码如下 复制代码

$this->checkLogin();

这样如果你没有登录则跳转到登录页面。并带上了你之前页面的url:


然后获取URL提交登录:

 代码如下 复制代码

public function login() {
        $url = $_GET['url'];
        $this->assign('url',$url);
        $this->assign('title','Login');
        $this->display('user/reg_new.html');
    }

模板上获取到url后提交到php后台,登录后跳转到这个url ok搞定

在php中下载文件我们用得最多的是直接使用readfile()函数,readfile()可以实现把服务器源文件给下载,下面我来给大家介绍readfile下载文件的方法与性能介绍

例1

 代码如下 复制代码

<?php
header(“Content-Type: text/html; charset=UTF-8″);
header(“Content-type:application/text”);

// 文件将被称为 downloaded.pdf
header(“Content-Disposition:attachment;filename=log.text”);

// PDF 源在 original.pdf 中
readfile(“ptindex_user_profilebasc.html”);

?>

例2

 代码如下 复制代码

 

 $item=trim($_GET['fileName']).".txt";  
    $abs_item='/usr/home/文件夹名称/文件夹名称/文件夹名称/'.$item;  
    $browser='IE';  
    header('Content-Type: '.(($browser=='IE' || $browser=='OPERA')?  
        'application/octetstream':'application/octet-stream'));  
    header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');  
    header('Content-Transfer-Encoding: binary');  
    header('Content-Length: '.filesize($abs_item));  
    if($browser=='IE') {  
        header('Content-Disposition: attachment; filename="'.$item.'"');  
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');  
        header('Pragma: public');  
    } else {  
        header('Content-Disposition: attachment; filename="'.$item.'"');  
        header('Cache-Control: no-cache, must-revalidate');  
        header('Pragma: no-cache');  
    }  
@readfile($abs_item); 

上面只能下载本地函数,如果要下载远程的我们可以如下操作PHP远程下载文件到本地的函数

 代码如下 复制代码

<?php

echo httpcopy("/baidu_sylogo1.gif");

function httpcopy($url, $file="", $timeout=60) {
    $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
            return $file;
        } else {
            return false;
        }
    } else {
        $opts = array(
            "http"=>array(
            "method"=>"GET",
            "header"=>"",
            "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            //$http_response_header
            return $file;
        } else {
            return false;
        }
    }
}
?>

最后分享一个支持多种文件下载的类函数

 代码如下 复制代码

<?php
/**
 * 使用方法:
 * require_once 'download.class.php';
 * $filepath = './path/filename.html';
 * $downname = 'downname.html';
 * $down = new download($filepath,$downname);
 * 或
 * $down = new download();
 *
 * */
class download
{
 var $filepath;
 var $downname;
 var $ErrInfo;
 var $is_attachment = false;
 var $_LANG = array(
   'err' => '错误',
   'args_empty' => '参数错误。',
   'file_not_exists' => '文件不存在!',
   'file_not_readable' => '文件不可读!',
  );
 var $MIMETypes = array(
   'ez' => 'application/andrew-inset',
   'hqx' => 'application/mac-binhex40',
   'cpt' => 'application/mac-compactpro',
   'doc' => 'application/msword',
   'bin' => 'application/octet-stream',
   'dms' => 'application/octet-stream',
   'lha' => 'application/octet-stream',
   'lzh' => 'application/octet-stream',
   'exe' => 'application/octet-stream',
   'class' => 'application/octet-stream',
   'so' => 'application/octet-stream',
   'dll' => 'application/octet-stream',
   'oda' => 'application/oda',
   'pdf' => 'application/pdf',
   'ai' => 'application/postscrīpt',
   'eps' => 'application/postscrīpt',
   'ps' => 'application/postscrīpt',
   'smi' => 'application/smil',
   'smil' => 'application/smil',
   'mif' => 'application/vnd.mif',
   'xls' => 'application/vnd.ms-excel',
   'ppt' => 'application/vnd.ms-powerpoint',
   'wbxml' => 'application/vnd.wap.wbxml',
   'wmlc' => 'application/vnd.wap.wmlc',
   'wmlsc' => 'application/vnd.wap.wmlscrīptc',
   'bcpio' => 'application/x-bcpio',
   'vcd' => 'application/x-cdlink',
   'pgn' => 'application/x-chess-pgn',
   'cpio' => 'application/x-cpio',
   'csh' => 'application/x-csh',
   'dcr' => 'application/x-director',
   'dir' => 'application/x-director',
   'dxr' => 'application/x-director',
   'dvi' => 'application/x-dvi',
   'spl' => 'application/x-futuresplash',
   'gtar' => 'application/x-gtar',
   'hdf' => 'application/x-hdf',
   'js' => 'application/x-javascrīpt',
   'skp' => 'application/x-koan',
   'skd' => 'application/x-koan',
   'skt' => 'application/x-koan',
   'skm' => 'application/x-koan',
   'latex' => 'application/x-latex',
   'nc' => 'application/x-netcdf',
   'cdf' => 'application/x-netcdf',
   'sh' => 'application/x-sh',
   'shar' => 'application/x-shar',
   'swf' => 'application/x-shockwave-flash',
   'sit' => 'application/x-stuffit',
   'sv4cpio' => 'application/x-sv4cpio',
   'sv4crc' => 'application/x-sv4crc',
   'tar' => 'application/x-tar',
   'tcl' => 'application/x-tcl',
   'tex' => 'application/x-tex',
   'texinfo' => 'application/x-texinfo',
   'texi' => 'application/x-texinfo',
   't' => 'application/x-troff',
   'tr' => 'application/x-troff',
   'roff' => 'application/x-troff',
   'man' => 'application/x-troff-man',
   'me' => 'application/x-troff-me',
   'ms' => 'application/x-troff-ms',
   'ustar' => 'application/x-ustar',
   'src' => 'application/x-wais-source',
   'xhtml' => 'application/xhtml+xml',
   'xht' => 'application/xhtml+xml',
   'zip' => 'application/zip',
   'au' => 'audio/basic',
   'snd' => 'audio/basic',
   'mid' => 'audio/midi',
   'midi' => 'audio/midi',
   'kar' => 'audio/midi',
   'mpga' => 'audio/mpeg',
   'mp2' => 'audio/mpeg',
   'mp3' => 'audio/mpeg',
   'wma' => 'audio/mpeg',
   'aif' => 'audio/x-aiff',
   'aiff' => 'audio/x-aiff',
   'aifc' => 'audio/x-aiff',
   'm3u' => 'audio/x-mpegurl',
   'ram' => 'audio/x-pn-realaudio',
   'rm' => 'audio/x-pn-realaudio',
   'rpm' => 'audio/x-pn-realaudio-plugin',
   'ra' => 'audio/x-realaudio',
   'wav' => 'audio/x-wav',
   'pdb' => 'chemical/x-pdb',
   'xyz' => 'chemical/x-xyz',
   'bmp' => 'image/bmp',
   'gif' => 'image/gif',
   'ief' => 'image/ief',
   'jpeg' => 'image/jpeg',
   'jpg' => 'image/jpeg',
   'jpe' => 'image/jpeg',
   'png' => 'image/png',
   'tiff' => 'image/tiff',
   'tif' => 'image/tiff',
   'djvu' => 'image/vnd.djvu',
   'djv' => 'image/vnd.djvu',
   'wbmp' => 'image/vnd.wap.wbmp',
   'ras' => 'image/x-cmu-raster',
   'pnm' => 'image/x-portable-anymap',
   'pbm' => 'image/x-portable-bitmap',
   'pgm' => 'image/x-portable-graymap',
   'ppm' => 'image/x-portable-pixmap',
   'rgb' => 'image/x-rgb',
   'xbm' => 'image/x-xbitmap',
   'xpm' => 'image/x-xpixmap',
   'xwd' => 'image/x-xwindowdump',
   'igs' => 'model/iges',
   'iges' => 'model/iges',
   'msh' => 'model/mesh',
   'mesh' => 'model/mesh',
   'silo' => 'model/mesh',
   'wrl' => 'model/vrml',
   'vrml' => 'model/vrml',
   'css' => 'text/css',
   'html' => 'text/html',
   'htm' => 'text/html',
   'asc' => 'text/plain',
   'txt' => 'text/plain',
   'rtx' => 'text/richtext',
   'rtf' => 'text/rtf',
   'sgml' => 'text/sgml',
   'sgm' => 'text/sgml',
   'tsv' => 'text/tab-separated-values',
   'wml' => 'text/vnd.wap.wml',
   'wmls' => 'text/vnd.wap.wmlscrīpt',
   'etx' => 'text/x-setext',
   'xsl' => 'text/xml',
   'xml' => 'text/xml',
   'mpeg' => 'video/mpeg',
   'mpg' => 'video/mpeg',
   'mpe' => 'video/mpeg',
   'qt' => 'video/quicktime',
   'mov' => 'video/quicktime',
   'mxu' => 'video/vnd.mpegurl',
   'avi' => 'video/x-msvideo',
   'movie' => 'video/x-sgi-movie',
   'wmv' => 'application/x-mplayer2',
   'ice' => 'x-conference/x-cooltalk',
  );
 
 function download($filepath='',$downname='')
 {
  if($filepath == '' AND !$this->filepath)
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['args_empty'];
   return false;
  }
  if($filepath == '') $filepath = $this->filepath;
  if(!file_exists($filepath))
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['file_not_exists'];
   return false;
  }
  if($downname == '' AND !$this->downname) $downname = $filepath;
  if($downname == '') $downname = $this->downname;
  // 文件扩展名
  $fileExt = substr(strrchr($filepath, '.'), 1);
  // 文件类型
  $fileType = $this->MIMETypes[$fileExt] ? $this->MIMETypes[$fileExt] : 'application/octet-stream';
  // 是否是图片
  $isImage = False;
  /*
  简述: getimagesize(), 详见手册
  说明: 判定某个文件是否为图片的有效手段, 常用在文件上传验证
  */
  $imgInfo = @getimagesize($filepath);
  if ($imgInfo[2] && $imgInfo['bits'])
  {
   $fileType = $imgInfo['mime'];  // 支持不标准扩展名
   $isImage = True;
  }
  // 显示方式
  if($this->is_attachment)
  {
   $attachment = 'attachment';  // 指定弹出下载对话框
  }
  else
  {
   $attachment = $isImage ? 'inline' : 'attachment';
  }
  // 读取文件
  if (is_readable($filepath))
  {
   /*
   简述: ob_end_clean() 清空并关闭输出缓冲, 详见手册
   说明: 关闭输出缓冲, 使文件片段内容读取至内存后即被送出, 减少资源消耗
   */
   ob_end_clean();
   /*
   HTTP头信息: 指示客户机可以接收生存期不大于指定时间(秒)的响应
   */
   header('Cache-control: max-age=31536000');
   /*
   HTTP头信息: 缓存文件过期时间(格林威治标准时)
   */
   header('Expires: ' . gmdate('D, d M Y H:i:s', time()+31536000) . ' GMT');
   /*
   HTTP头信息: 文件在服务期端最后被修改的时间
   Cache-control,Expires,Last-Modified 都是控制浏览器缓存的头信息
   在一些访问量巨大的门户, 合理的设置缓存能够避免过多的服务器请求, 一定程度下缓解服务器的压力
   */
   header('Last-Modified: ' . gmdate('D, d M Y H:i:s' , filemtime($filepath) . ' GMT'));
   /*
   HTTP头信息: 文档的编码(Encode)方法, 因为附件请求的文件多样化, 改变编码方式有可能损坏文件, 故为none
   */
   header('Content-Encoding: none');
   /*
   HTTP头信息: 告诉浏览器当前请求的文件类型.
   1.始终指定为application/octet-stream, 就代表文件是二进制流, 始终提示下载.
   2.指定对应的类型, 如请求的是mp3文件, 对应的MIME类型是audio/mpeg, IE就会自动启动Windows Media Player进行播放.
   */
   header('Content-type: ' . $fileType);
   /*
   HTTP头信息: 如果为attachment, 则告诉浏览器, 在访问时弹出”文件下载”对话框, 并指定保存时文件的默认名称(可以与服务器的文件名不同)
   如果要让浏览器直接显示内容, 则要指定为inline, 如图片, 文本
   */
   header('Content-Disposition: ' . $attachment . '; filename=' . $downname);
   /*
   HTTP头信息: 告诉浏览器文件长度
   (IE下载文件的时候不是有文件大小信息么?)
   */
   header('Content-Length: ' . filesize($filepath));
   // 打开文件(二进制只读模式)
   $fp = fopen($filepath, 'rb');
   // 输出文件
   fpassthru($fp);
   // 关闭文件
   fclose($fp);
   return true;
  }
  else
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['file_not_readable'];
   return false;
  }
 }
}
?>

本文章来给大家推荐一个不错的购物车效果,这里主要求包括了几个东西,一个是购物车类用php写的, 还有一个Ajax操作用到了jquery,还有一个jquery插件thickbox了,下面我们来看看。

购物车类:shop_cart.php
购物车的操作:cart_action.php
首页:index.html
Ajax操作用到了jquery,还有一个jquery插件thickbox

不多说了你可以先看看效果示例
shop_cart.php当然是购物车的核心,但是这个类很简单,因为他又引进了cart_action.php用于对外操作。所以这个类显得相当精简。
购物车类shop_cart.php

 代码如下 复制代码

cart_name = $name;
$this->items = $_SESSION[$this->cart_name];
}

/**
* setItemQuantity() - Set the quantity of an item.
*
* @param string $order_code The order code of the item.
* @param int $quantity The quantity.
*/
function setItemQuantity($order_code, $quantity) {
$this->items[$order_code] = $quantity;
}

/**
* getItemPrice() - Get the price of an item.
*
* @param string $order_code The order code of the item.
* @return int The price.
*/
function getItemPrice($order_code) {
// This is where the code taht retrieves prices
// goes. We'll just say everything costs $9.99 for this tutorial.
return 9.99;
}

/**
* getItemName() - Get the name of an item.
*
* @param string $order_code The order code of the item.
*/
function getItemName($order_code) {
// This is where the code that retrieves product names
// goes. We'll just return something generic for this tutorial.
return 'My Product (' . $order_code . ')';
}

/**
* getItems() - Get all items.
*
* @return array The items.
*/
function getItems() {
return $this->items;
}

/**
* hasItems() - Checks to see if there are items in the cart.
*
* @return bool True if there are items.
*/
function hasItems() {
return (bool) $this->items;
}

/**
* getItemQuantity() - Get the quantity of an item in the cart.
*
* @param string $order_code The order code.
* @return int The quantity.
*/
function getItemQuantity($order_code) {
return (int) $this->items[$order_code];
}

/**
* clean() - Cleanup the cart contents. If any items have a
*           quantity less than one, remove them.
*/
function clean() {
foreach ( $this->items as $order_code=>$quantity ) {
if ( $quantity < 1 )     unset($this->items[$order_code]);
}
}

/**
* save() - Saves the cart to a session variable.
*/
function save() {
$this->clean();
$_SESSION[$this->cart_name] = $this->items;
}
}

?>

对于cart_action,他实现了shop_cart类与index的中间作用,用于更新,删除,增加商品的操作。
cart_action.php

 代码如下 复制代码

getItemQuantity($_GET['order_code'])+$_GET['quantity'];
$Cart->setItemQuantity($_GET['order_code'], $quantity);
}else{

if ( !empty($_GET['quantity']) ) {
foreach ( $_GET['quantity'] as $order_code=>$quantity){
$Cart->setItemQuantity($order_code, $quantity);
}
}

if ( !empty($_GET['remove']) ) {
foreach ( $_GET['remove'] as $order_code ) {
$Cart->setItemQuantity($order_code, 0);
}
}
}
$Cart->save();

header('Location: cart.php');

?>

还有就是index.html实现对外的操作,也就是添加操作

 代码如下 复制代码

<!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>Shopping Cart</title>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.color.js" type="text/javascript"></script>
<script src="js/thickbox.js" type="text/javascript"></script>
<script src="js/cart.js" type="text/javascript"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/thickbox.css" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript">
$(function() {
$("form.cart_form").submit(function() {
var title = "Your Shopping Cart";
var orderCode = $("input[name=order_code]", this).val();
var quantity = $("input[name=quantity]", this).val();
var url = "cart_action.php?order_code=" + orderCode + "&amp;amp;amp;amp;amp;amp;amp;quantity=" + quantity + "&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780";
tb_show(title, url, false);

return false;
});
});
</script>
</head>
<body>
<div id="container">
<h1>购物车</h1>
<a href="cart.php?KeepThis=true&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">打开购物车</a>
<hr />
<a href="cart_action.php?order_code=KWL-JFE&amp;amp;amp;amp;amp;amp;amp;quantity=3&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">添加三个 KWL-JFE 到购物车</a>
<hr />
<form class="cart_form" action="cart_action.php" method="get">
<input type="hidden" name="order_code" value="KWL-JFE" />
<label>KWL-JFE: <input class="center" type="text" name="quantity" value="1" size="3" ?></label>
<input type="submit" name="submit" value="添加到购物车" />
</form>
</div>
</body>
</html>

还有就是cart.php这是我们的购物车

 代码如下 复制代码
<?php
include('shopping_cart.class.php');
session_start();
$Cart = new Shopping_Cart('shopping_cart');
?>
<!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">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<head>
<title>Shopping Cart</title>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.color.js" type="text/javascript"></script>
<script src="js/cart.js" type="text/javascript"></script>
<link href="css/cart.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="container">
<h1>Shopping Cart</h1>
<?php if ( $Cart->hasItems() ) : ?>
<form action="cart_action.php" method="get">
<table id="cart">
<tr>
<th>数量</th>
<th>商品名称</th>
<th>商品编号</th>
<th>单价</th>
<th>总价</th>
<th>删除</th>
</tr>
<?php
$total_price = $i = 0;
foreach ( $Cart->getItems() as $order_code=>$quantity ) :
$total_price += $quantity*$Cart->getItemPrice($order_code);
?>
<?php echo $i++%2==0 ? "<tr>" : "<tr class='odd'>"; ?>
<td class="quantity center"><input type="text" name="quantity[<?php echo $order_code; ?>]" size="3" value="<?php echo $quantity; ?>" tabindex="<?php echo $i; ?>" /></td>
<td class="item_name"><?php echo $Cart->getItemName($order_code); ?></td>
<td class="order_code"><?php echo $order_code; ?></td>
<td class="unit_price">$<?php echo $Cart->getItemPrice($order_code); ?></td>
<td class="extended_price">$<?php echo ($Cart->getItemPrice($order_code)*$quantity); ?></td>
<td class="remove center"><input type="checkbox" name="remove[]" value="<?php echo $order_code; ?>" /></td>
</tr>
<?php endforeach; ?>
<tr><td colspan="2"></td><td  colspan="3" id="total_price">您的消费总金额是:¥<?php echo $total_price; ?></td></tr>
</table>
<input type="submit" name="update" value="保存购物车" />
</form>
<?php else: ?>
<p class="center">您还没有购物.</p>
<?php endif; ?>
<p><a href="load.php">加载简单的购物车</a></p>
</div>
</body>
</html>

php 创建文件的方法有很多种我们最常用的就是fopen,file_put_contents这两种方法来创建文件了,下面我来给大家详细介绍介绍,有需要了解的同学可参考。

创建php文件

 代码如下 复制代码

<?php
$str="<?php echo 123;?>";
file_put_contents('test.php',$str);//使用脚本创建一个php文件
?>

例2

 代码如下 复制代码

<?php
if ($argc != 2) {
die("Usage: php mkphp.php filename");
}
array_shift($argv);
$cat= $argv[0];
file_put_contents($cat.".php", "<?php

?>");

利用fopen创建文件

 代码如下 复制代码

<?

$fp=fopen("1.txt","w+");//fopen()的其它开关请参看相关函数
$str="我加我加我加加加";
fputs($fp,$str);
fclose($fp);
?>

上面没作任何考虑,如果要全面点我们首先,确定你所要新建文件所在的目录权限; 建议设备为777。然后,新建文件的名称建议使用绝对路径。

 代码如下 复制代码

<?php
$filename="test.txt";
$fp=fopen("$filename", "w+"); //打开文件指针,创建文件
if ( !is_writable($filename) ){
      die("文件:" .$filename. "不可写,请检查!");
}
//fwrite($filename, "anything you want to write to $filename.";
fclose($fp);  //关闭指针

'r' 开文件方式为只读,文件指’指到开始处
'r+' 开文件方式为可读写,文件指’指到开始处
'w' 开文件方式为写入,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'w+' 开文件方式为可读写,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'a' 开文件方式为写入,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'a+' 开文件方式为可读写,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'b' 若操作系统的文字及二进位文件不同,‘可以用“‘”,UNIX 系统不–要“用 参”。

 代码如下 复制代码

///创建文件
function creat_file($PATH){
   $sFile = "test.html";
   if (file_exists($PATH.$sFile)) {
    creat_file();
   } else {
    $fp= fopen($PATH.$sFile,"w");
    fclose($fp);
   }
   return $sFile;
}

[!--infotagslink--]

相关文章

  • php KindEditor文章内分页的实例方法

    我们这里介绍php与KindEditor编辑器使用时如何利用KindEditor编辑器的分页功能实现文章内容分页,KindEditor编辑器在我们点击分页时会插入代码,我们只要以它为分切符,就...2016-11-25
  • 自己动手写的jquery分页控件(非常简单实用)

    最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • jQuery 2.0.3 源码分析之core(一)整体架构

    拜读一个开源框架,最想学到的就是设计的思想和实现的技巧。废话不多说,jquery这么多年了分析都写烂了,老早以前就拜读过,不过这几年都是做移动端,一直御用zepto, 最近抽出点时间把jquery又给扫一遍我也不会照本宣科的翻译...2014-05-31
  • vue.js 表格分页ajax 异步加载数据

    Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.这篇文章主要介绍了vue.js 表格分页ajax 异步加载数据的相关资料,需要的朋友可以参考下...2016-10-20
  • Springboot如何使用mybatis实现拦截SQL分页

    这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19
  • PHP 一个完整的分页类(附源码)

    在php中要实现分页比起asp中要简单很多了,我们核心就是直接获取当前页面然后判断每页多少再到数据库中利用limit就可以实现分页查询了,下面我来详细介绍分页类实现程序...2016-11-25
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • 基于jquery实现表格无刷新分页

    这篇文章主要介绍了基于jquery实现表格无刷新分页,功能实现了前端排序功能,增加了前端搜索功能,感兴趣的小伙伴们可以参考一下...2016-01-08
  • AngularJS实现分页显示数据库信息

    这篇文章主要为大家详细介绍了AngularJS实现分页显示数据库信息效果的相关资料,感兴趣的小伙伴们可以参考一下...2016-07-06
  • vue实现页面打印自动分页的两种方法

    这篇文章主要为大家详细介绍了vue实现页面打印自动分页的两种方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-29
  • vue3源码剖析之简单实现方法

    源码的重要性相信不用再多说什么了吧,特别是用Vue 框架的,一般在面试的时候面试官多多少少都会考察源码层面的内容,下面这篇文章主要给大家介绍了关于vue3源码剖析之简单实现的相关资料,需要的朋友可以参考下...2021-09-07
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • C# DataTable分页处理实例代码

    有时候我们从数据库获取的数据量太大,而我们不需要一次性显示那么多的时候,我们就要对数据进行分页处理了,让每页显示不同的数据。...2020-06-25
  • 原生js实现分页效果

    这篇文章主要为大家详细介绍了原生js实现分页效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-09-24
  • Python优化列表接口进行分页示例实现

    最近,在做测试开发平台的时候,需要对测试用例的列表进行后端分页,在实际去写代码和测试的过程中,发现这里面还是有些细节的,故想复盘一下...2021-09-29
  • vue.js表格分页示例

    这篇文章主要为大家详细介绍了vue.js表格分页示例,ajax异步加载数据...2016-10-20
  • laypage分页控件使用实例详解

    这篇文章主要为大家详细分享了laypage分页控件使用实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-05-20
  • 解析iReport自定义行数分页的操作方法

    ireport默认都是自动分页数据超出页面长度就会自动分到下一页,但有时候业务需要一页只显示固定几行这时候就需要自定义条数了。下面看具体操作吧...2021-10-26