php文件上传类与详解(1/2)
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(); //上传文件;
}
}
两款超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."]条数据";
}
}
<!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 */
一. 什么是memcached
memcached 是一个高性能的分布式内存对象缓存系统,用于动态web应用以减轻数据库教程负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态、数据库驱动网站的速度。
相信很多人都用过缓存,在 .net 中也有内置的缓存机制,还有很多第三方工具如apache,nginx等可以做静态资源的缓存,同时我们也可以制定自己的缓存机制,缓存数据库查询的数据以减少对数据库的频繁操作。但是很多时候我们总是感觉这些缓存总不尽人意, memcached可以解决你不少的烦恼问题。最少在我的学习中解决了我不少问题,所以决定记录下来分享。
memcached基于一个存储键/值对的hashmap。其守护进程是用c写的,但是客户端可以用任何语言来编写(本文使用c#作为例子),并通过memcached协议与守护进程通信。可 能这些东西都太高深了,我们暂不做研究。
二. 分布式缓存
其实 memcached作为一个分布式缓存数据服务,但是每个服务之间根本没有进行相互通信,这里可能与我理解的分布式有点区别,可能是我才疏学浅,也可能是每个人思考问题的角度不同。memcached 客户端就是通过一种分布式算法将数据保存到不同的memcached服务器上,将数据进行缓存。分布式缓存,可以而知memcached可以进行大数据量的缓存。这点可以弥补我们之前很多人都遇到的将数据缓存到应用服务器上,而且只能缓存少量数据,否则对应用服务器的影响非常大。
memcached应用机制图:
这个图是有点简陋了,但是问题还是能够描述的清楚的,缓存机制的基本原理就是先查询数据保存到memcached中,地址在此请求就直接从memcached缓存中取数据,这样就可以减少对服务器请求压力。
相关文章
- 下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
Jupyter Notebook读取csv文件出现的问题及解决
这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06- 有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
php无刷新利用iframe实现页面无刷新上传文件(1/2)
利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25- 本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
- 要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
- 又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
- 本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
- 今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
- 这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
- 步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
- 本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
- 这篇文章主要介绍了C#使用StreamWriter写入文件的方法,涉及C#中StreamWriter类操作文件的相关技巧,需要的朋友可以参考下...2020-06-25
ant design中upload组件上传大文件,显示进度条进度的实例
这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29- 举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
- 这篇文章主要介绍了C#路径,文件,目录及IO常见操作,较为详细的分析并汇总了C#关于路径,文件,目录及IO常见操作,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25