首页 > 编程技术 > php

php中登录后跳转回原来要访问的页面实例

发布时间:2016-11-25 17:28

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

最简单的办法就是直接使用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数组中分为数组值与数组key,下面小编来给大家总结一下在php中数组值常用的操作方法包括有:数组中加入数值、判断 数组中的数值、删除特定数组值等有需要的同学可参考。

php删除特定数组值

首先

 代码如下 复制代码
var_dump($context['linktree']);

得到

 代码如下 复制代码
array(3) {
[0]=>
array(2) {
["url"]=>
string(52) “http://127.0.0.1/testforum.cityofsteam.com/index.php”
["name"]=>
string(28) “City of Steam Official Forum”
}
[1]=>
array(2) {
["url"]=>
string(55) “http://127.0.0.1/testforum.cityofsteam.com/index.php#c1″
["name"]=>
string(28) “City of Steam Official Forum”
}
[2]=>
array(2) {
["url"]=>
string(62) “http://127.0.0.1/testforum.cityofsteam.com/index.php?board=4.0″
["name"]=>
string(12) “Announcement”
}
}

我要去掉中间那个。

用:unset($context['linktree']['1']);

结果:

 代码如下 复制代码

array(2) {
[0]=>
array(2) {
["url"]=>
string(52) “http://127.0.0.1/testforum.cityofsteam.com/index.php”
["name"]=>
string(28) “City of Steam Official Forum”
}
[2]=>
array(2) {
["url"]=>
string(62) “http://127.0.0.1/testforum.cityofsteam.com/index.php?board=4.0″
["name"]=>
string(12) “Announcement”
}
}

就少了一个[1]

让这中间的1自动编号:

 代码如下 复制代码


Array ( [0] => apple [1] => banana [3] => dog )

但是这种方法的最大缺点是没有重建数组索引,就是说,数组的第三个元素没了。
经过查资料后,原来PHP提供了这个功能,只不过很间接。这个函数是array_splice()。
为了使用方便,我封装成了一个函数,方便大家使用:

 代码如下 复制代码

<?php

function array_remove(&$arr, $offset)

{
 
array_splice($arr, $offset, 1);

}

$arr = array('apple','banana','cat','dog');
 
array_remove($arr, 2);
 
print_r($arr);

?>

经过测试可以知道,2的位置这个元素被真正的删除了,并且重新建立了索引。

程序运行结果:

 代码如下 复制代码

Array ( [0] => apple [1] => banana [2] => dog )


php判断 数组中的数值


有专门的函数,不要用for循环,系统函数能实现快速搜索:

in_array
(PHP 4, PHP 5)

in_array — 检查数组中是否存在某个值

说明
bool in_array ( mixed $needle, array $haystack [, bool $strict] )

在 haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE。

如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。

注意: 如果 needle 是字符串,则比较是区分大小写的。

注意: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。

例 292. in_array() 例子

 代码如下 复制代码
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

第二个条件失败,因为 in_array() 是区分大小写的,所以以上程序显示为:

Got Irix

例 293. in_array() 严格类型检查例子

 代码如下 复制代码

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict checkn";
}
if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict checkn";
}
?>
上例将输出:

1.13 found with strict check

例 294. in_array() 中用数组作为 needle

 代码如下 复制代码

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was foundn";
}
if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was foundn";
}
if (in_array('o', $a)) {
    echo "'o' was foundn";
}
?>
上例将输出:

  'ph' was found
  'o' was found


向一个数组中加入数值

我们可以通过函数来实现,将一个或多个元素插入到数组中去,也可以直接添加进去。
(1)向数组中直接添加数据,新元素的下标是从原数组下标最大值之后开始的。
(2)array_unshift()函数在数组的开头添加一个或多个元素。
语法如下:
int array_unshift ( array &array, mixed var [,mixed ...]) ;
array_unshift()将传入的元素插入到array数组的开头。元素是作为整体被插入的,传入元素将保持同样的顺序。所有的数值键名将从0开始重新计数,文字键名保持不变。
(3)array_push()函数将一个或多个单元添加到数组的末尾。
语法:
int array_push ( array &array, mixed var [, mixed ...]) ;
array_push()将array当成一个栈,并将传入的变量添加到array的末尾。该函数返回数组新的单元总数。向数组中添加数据的示例如下。
示例:

 代码如下 复制代码
<?php
$shili = array (“1″,”2″,”3″,”4″) ;
$shili[]=5 ;                            //直接添加数据
print_r ( $shili ) ;
echo “<br>” ;
$shili2 = array (“m”,”n”) ;
array_unshift ($shili2,”o”,”p”) ;          //添加元素于数组的开头
print_r ( $shili2 ) ;
echo “<br>” ;
$shili3 = array (“Php”) ;
array_push ($shili3, “MySQL”,”Apache”) ; //添加元素于数组的末尾
print_r ($shili3) ;
?>
结果为:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Array ( [0] => o [1] => p [2] => m [3] => n )
Array ( [0] => Php [1] => MySQL [2] => Apache )
在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中下载文件我们用得最多的是直接使用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" width=100% src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script" width=100% src="js/jquery.color.js" type="text/javascript"></script>
<script" width=100% src="js/thickbox.js" type="text/javascript"></script>
<script" width=100% 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" width=100% src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script" width=100% src="js/jquery.color.js" type="text/javascript"></script>
<script" width=100% 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>

标签:[!--infotagslink--]

您可能感兴趣的文章: