三款php多文件上传实例代码(1/3)

 更新时间:2016年11月25日 16:26  点击:1288
在php开发应用中经常会碰到文件上传这个需,有时也会碰到要多文件上传,下面我们就来看看我提供的三款php多文件上传实例代码,好了费话不说多了来看看这些多文件上传功能适合你么。

示例代码:

 代码如下 复制代码
<form action="" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile[]">   命名必是这样有"[]"
<input type="file" name="uploadfile[]">

//设置允许用户上传的文件类型。
$type = array('gif', 'jpg', 'png', 'zip', 'rar');
$upload = new uploadfile($_files['uploadfile'], '/', 1024*1024, $type);
参数说明:1:表单的文件,2:上传目录,3:支持文件大小,4:允许文件类型
$icount = $upload->upload();
if($icount > 0) { //上传成功
   print_r($upload->getsaveinfo());
  */

class uploadfile {
var $postfile = array();       // 用户上传的文件
var $custompath = "";          // 自定义文件上传路径
var $maxsize = "";             // 文件最大尺寸
var $lasterror = "";           // 最后一次出错信息
var $allowtype = array('gif', 'jpg', 'png', 'zip', 'rar', 'txt', 'doc', 'pdf');
var $endfilename = "";         // 最终保存的文件名
var $saveinfo = array();       // 保存文件的最终信息
var $root_dir = ""; // 项目在硬盘上的位置

/**
* 构造函数
* @access public
*/

 代码如下 复制代码
function uploadfile($arrfile, $path="_", $size = 2097152, $type = 0) {
   $this->postfile     = $arrfile;
   $this->custompath   = $path == "_" ? "" : $path ;
   $this->maxsize      = $size;
   if($type!=0)   $this->allowtype   = $arrfile;
   $this->root_dir      = $_server['document_root'];
   $this->_mkdir($this->custompath);
}

/**
* 文件上传的核心代码
* @access public
* @return int 上传成功文件数
*/

 代码如下 复制代码

function upload() {
   $ilen = sizeof($this->postfile['name']);
   for($i=0;$i<$ilen;$i++){
    if ($this->postfile['error'][$i] == 0) { //上传时没有发生错误
      //取当前文件名、临时文件名、大小、扩展名,后面将用到。
     $sname   = $this->postfile['name'][$i];
     $stname = $this->postfile['tmp_name'][$i];
     $isize   = $this->postfile['size'][$i];
     $stype   = $this->postfile['type'][$i];
     $sextn   = $this->_getextname($sname);
   
     //检测当前上传文件大小是否合法。
     if($this->_checksize){
      $this->lasterror = "您上传的文件[".$sname."],超过系统支持大小!";
      $this->_showmsg($this->lasterror);
      continue;
     }

     if(!is_uploaded_file($stname)) {
      $this->lasterror = "您的文件不是通过正常途径上传!";
      $this->_showmsg($this->lasterror);
      continue;
     }
     $_filename = basename($sname,".".$sextn)."_".time().".".$sextn;
     $this->endfilename = $this->custompath.$_filename;
   
     if(!move_uploaded_file($stname, $this->root_dir.$this->endfilename)) {
      $this->lasterror = $this->postfile['error'][$i];
      $this->_showmsg($this->lasterror);
      continue;
     }

     //存储当前文件的有关信息,以便其它程序调用。
     $this->save_info[] =   array("name" => $sname, "type" => $sextn, "size" => $isize,   "path" => $this->endfilename);
    }
   }

   return sizeof($this->save_info);
}

 

提供一款国人写的留言板,他是利用了jquery php mysql ajax来实现php ajax 局部刷新留方板实例的喜欢就下载吧。

*/

 代码如下 复制代码

$link = @mysql_connect($db_host,$db_user,$db_pass) or die('unable to establish a db connection');

mysql_query("set names 'utf8'");
mysql_select_db($db_database,$link);

class comment
{
 private $data = array();
 
 public function __construct($row)
 {
  /*
  / the constructor
  */
  
  $this->data = $row;
 }
 
 public function markup()
 {
  /*
  / this method outputs the xhtml markup of the comment
  */
  
  // setting up an alias, so we don't have to write $this->data every time:
  $d = &$this->data;
  
  $link_open = '';
  $link_close = '';
  
  if($d['url']){
   
   // if the person has entered a url when adding a comment,
   // define opening and closing hyperlink tags
   
   $link_open = '<a href="'.$d['url'].'">';
   $link_close =  '</a>';
  }
  
  // converting the time to a unix timestamp:
  $d['dt'] = strtotime($d['dt']);
  
  // needed for the default gravatar image:
  $url = 'http://'.dirname($_server['server_name'].$_server["request_uri"]).'/img/default_avatar.gif';
  
  return '
  
   <div class="comment">
    <div class="avatar">
     '.$link_open.'
     <img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&amp;default='.urlencode($url).'" />
     '.$link_close.'
    </div>
    
    <div class="name">'.$link_open.$d['name'].$link_close.'</div>
    <div class="date" title="added at '.date('h:i on d m y',$d['dt']).'">'.date('d m y',$d['dt']).'</div>
    <p>'.$d['body'].'</p>
   </div>
  ';
 }
 
 public static function validate(&$arr)
 {
  /*
  / this method is used to validate the data sent via ajax.
  /
  / it return true/false depending on whether the data is valid, and populates
  / the $arr array passed as a paremter (notice the ampersand above) with
  / either the valid input data, or the error messages.
  */
  
  $errors = array();
  $data = array();
  
  // using the filter_input function introduced in php 5.2.0
  
  if(!($data['email'] = filter_input(input_post,'email',filter_validate_email)))
  {
   $errors['email'] = 'please enter a valid email.';
  }
  
  if(!($data['url'] = filter_input(input_post,'url',filter_validate_url)))
  {
   // if the url field was not populated with a valid url,
   // act as if no url was entered at all:
   
   $url = '';
  }
  
  // using the filter with a custom callback function:
  
  if(!($data['body'] = filter_input(input_post,'body',filter_callback,array('options'=>'comment::validate_text'))))
  {
   $errors['body'] = 'please enter a comment body.';
  }
  
  if(!($data['name'] = filter_input(input_post,'name',filter_callback,array('options'=>'comment::validate_text'))))
  {
   $errors['name'] = 'please enter a name.';
  }
  
  if(!empty($errors)){
   
   // if there are errors, copy the $errors array to $arr:
   
   $arr = $errors;
   return false;
  }
  
  // if the data is valid, sanitize all the data and copy it to $arr:
  
  foreach($data as $k=>$v){
   $arr[$k] = mysql_real_escape_string($v);
  }
  
  // ensure that the email is lower case:
  
  $arr['email'] = strtolower(trim($arr['email']));
  
  return true;
  
 }

 private static function validate_text($str)
 {
  /*
  / this method is used internally as a filter_callback
  */
  
  if(mb_strlen($str,'utf8')<1)
   return false;
  
  // encode all html special characters (<, >, ", & .. etc) and convert
  // the new line characters to <br> tags:
  
  $str = nl2br(htmlspecialchars($str));
  
  // remove the new line characters that are left
  $str = str_replace(array(chr(10),chr(13)),'',$str);
  
  return $str;
 }

}

$comments = array();
$result = mysql_query("select * from comments order by id asc");

while($row = mysql_fetch_assoc($result))
{
 $comments[] = new comment($row);
}

?>

<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>simple ajax commenting system | tutorialzine demo</title>

<link rel="stylesheet" type="text/css教程" href="styles.css" />

</head>

<body>

 


<div id="main">

<?php

/*
/ output the comments one by one:
*/

foreach($comments as $c){
 echo $c->markup();
}

?>

<div id="addcommentcontainer">
 <p>add a comment</p>
 <form id="addcommentform" method="post" action="">
     <div>
         <label for="name">your name</label>
         <input type="text" name="name" id="name" />
           
            <label for="email">your email</label>
            <input type="text" name="email" id="email" />
           
            <label for="url">website (not required)</label>
            <input type="text" name="url" id="url" />
           
            <label for="body">comment body</label>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>
           
            <input type="submit" id="submit" value="submit" />
        </div>
    </form>
</div>

</div>

<script type="text/网页特效" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

</body>
</html>

数据库教程结构

 代码如下 复制代码

--
-- table structure for table `comments`
--

create table `comments` (
  `id` int(10) unsigned not null auto_increment,
  `name` varchar(128) collate utf8_unicode_ci not null default '',
  `url` varchar(255) collate utf8_unicode_ci not null default '',
  `email` varchar(255) collate utf8_unicode_ci not null default '',
  `body` text collate utf8_unicode_ci not null,
  `dt` timestamp not null default '0000-00-00',
  primary key  (`id`)
) engine=myisam  default charset=utf8 collate=utf8_unicode_ci;

本文章是利用了php一个插件实例邮php文件上传进度条的功能,方法比较简单,因为都有组件了,所以只要按照人家的意思照办就可以实例php大文件上传的功能了。

目前我知道的方法有两种,一种是使用php的创始人 rasmus lerdorf 写的apc扩展模块来实现(http://pecl.php.net/package/apc),另外一种方法是使用pecl扩展模块uploadprogress实现(http://pecl.php.net/package/uploadprogress) 我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。

apc实现方法:

安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷,这里不说明

配置php.ini,设置参数 apc.rfc1867=1 ,使apc支持上传进度条功能,在apc源码说明文档里面有说明

 

php文件上传进度条实现方法:安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷,这里不说明 配置php.ini,设置参数 apc.rfc1867=1 ,使apc支持上传进度条功能,在apc源码说明文档里面有说明 代码范例:

if($_server['request_method']=='post'){//上传请求
$status=apc_fetch('upload_'.$_post['apc_upload_progress']);
$status['done']=1;
echojson_encode($status);//输出给用户端页面里的ajax调用,相关文档请自己寻找
exit;
}elseif(isset($_get['progress_key'])){//读取上传进度
$status=apc_fetch('upload_'.$_get['progress_key']);
echojson_encode($status);
exit;
}else{
//其他代码,比如上传表单等
}
uploadprogress 模块实现方法:使用pecl模块安装方法安装该模块的php文件上传进度条实现方法 php.ini里面设置 uploadprogress.file.filename_template = "/tmp/upd_%s.txt"

if($_server['request_method']=='post'){
if(is_uploaded_file($_files['upfile']['tmp_name'])){
$upload_dir='your_path/';
$ext=strrchr($_files['video']['name'],'.');
$sessid=$_post['upload_identifier'];
$tmpfile=$upload_dir.$sessid;
$sessfile=$upload_dir.$sessid.$ext;
if(move_uploaded_file($_files['upfile']['tmp_name'],$tmpfile)){
//上传成功
}else{
//上传失败
}else{
//上传错误

}elseif(!empty($_get['sessid'])){
header("expires:mon,26jul199705:00:00gmt");
header("last-modified:".gmdate("d,dmyh:i:s")."gmt");
header("cache-control:no-store,no-cache,must-revalidate");
header("cache-control:post-check=0,pre-check=0′,false);
header("pragma:no-cache");
header("content-type:text/html;charset=utf-8′);

$unique_id=$_get['sessid'];
$uploadvalues=uploadprogress_get_info($unique_id);

if(is_array($uploadvalues)){
echo  json_encode($uploadvalues);
}else{
//读取进度失败,另外处理逻辑
}

}else{
//显示上传表单
}


pecl扩展模块uploadprogress实现。


基于php的ajax技术的具体应用解析
php限制上传文件大小的具体解决办法
php批量上传图片的具体实现方式
php动态多文件上传的具体代码分享
php通用文件上传类的具体解析 我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。

apc的php文件上传进度条实现方法:

安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷

 <?php教程
/**
*十进制转二进制、八进制、十六进制 不足位数前面补零*
*
* @param array $datalist 传入数据array(100,123,130)
* @param int $bin 转换的进制可以是:2,8,16
* @return array 返回数据 array() 返回没有数据转换的格式
* @copyright chengmo qq:8292669
*/
function decto_bin($datalist,$bin)
{
static $arr=array(0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f');
if(!is_array($datalist)) $datalist=array($datalist);
if($bin==10)return $datalist; //相同进制忽略
$bytelen=ceil(16/$bin); //获得如果是$bin进制,一个字节的长度
$aoutchar=array();
foreach ($datalist as $num)
{
$t="";
$num=intval($num);
if($num===0)continue;
while($num>0)
{
$t=$arr[$num%$bin].$t;
$num=floor($num/$bin);
}
$tlen=strlen($t);
if($tlen%$bytelen!=0)
{
$pad_len=$bytelen-$tlen%$bytelen;
$t=str_pad("",$pad_len,"0",str_pad_left).$t; //不足一个字节长度,自动前面补充0
}
$aoutchar[]=$t;
}
return $aoutchar;
}

文章提供一款php检测文件类型(根据文件header信息)哦,他可以根据用户发布的文件头部信息来确实文件的类型。
 代码如下 复制代码
<?php
/*通过文件名,获得文件类型*
*@author chengmo*
*@copyright cnblog.com/chengmo 2010-10-17
*@version 0.1
*$filename="d:/1.png";echo cfiletypecheck::getfiletype($filename); 打印:png
*/
class cfiletypecheck
{
private static $_typelist=array();
private static $checkclass=null;
private function __construct($filename)
{
self::$_typelist=$this->gettypelist();
}
/**
*处理文件类型映射关系表*
*
* @param string $filename 文件类型
* @return string 文件类型,没有找到返回:other
*/
private function _getfiletype($filename)
{
$filetype="other";
if(!file_exists($filename)) throw new exception("no found file!");
$file = @fopen($filename,"rb");
if(!$file) throw new exception("file refuse!");
$bin = fread($file, 15); //只读15字节 各个不同文件类型,头信息不一样。
fclose($file);
$typelist=self::$_typelist;
foreach ($typelist as $v)
{
$blen=strlen(pack("h*",$v[0])); //得到文件头标记字节数
$tbin=substr($bin,0,intval($blen)); ///需要比较文件头长度
if(strtolower($v[0])==strtolower(array_shift(unpack("h*",$tbin))))
{
return $v[1];
}
}
return $filetype;
}
/**
*得到文件头与文件类型映射表*
*
* @return array array(array('key',value)...)
*/
public function gettypelist()
{
return array(array("ffd8ffe1","jpg"),
array("89504e47","png"),
array("47494638","gif"),
array("49492a00","tif"),
array("424d","bmp"),
array("41433130","dwg"),
array("38425053","ps教程d"),
array("7b5c727466","rtf"),
array("3c3f786d6c","xml"),
array("68746d6c3e","html"),
array("44656c69766572792d646174","eml"),
array("cfad12fec5fd746f","dbx"),
array("2142444e","pst"),
array("d0cf11e0","xls/doc"),
array("5374616e64617264204a","mdb"),
array("ff575043","wpd"),
array("252150532d41646f6265","eps/ps"),
array("255044462d312e","pdf"),
array("e3828596","pwl"),
array("504b0304","zip"),
array("52617221","rar"),
array("57415645","wav"),
array("41564920","avi"),
array("2e7261fd","ram"),
array("2e524d46","rm"),
array("000001ba","mpg"),
array("000001b3","mpg"),
array("6d6f6f76","mov"),
array("3026b2758e66cf11","asf"),
array("4d546864","mid"));
}
public static function getfiletype($filename)
{
if(!self::$checkclass) self::$checkclass=new self($filename);
$class=self::$checkclass;
return $class->_getfiletype($filename);
}
}
[!--infotagslink--]

相关文章

  • php读取zip文件(删除文件,提取文件,增加文件)实例

    下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
  • Jupyter Notebook读取csv文件出现的问题及解决

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • Photoshop打开PSD文件空白怎么解决

    有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • C#实现HTTP下载文件的方法

    这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • php批量替换内容或指定目录下所有文件内容

    要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
  • AI源文件转photoshop图像变模糊问题解决教程

    今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
  • C++万能库头文件在vs中的安装步骤(图文)

    这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • php文件上传你必须知道的几点

    本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
  • ant design中upload组件上传大文件,显示进度条进度的实例

    这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29
  • C#使用StreamWriter写入文件的方法

    这篇文章主要介绍了C#使用StreamWriter写入文件的方法,涉及C#中StreamWriter类操作文件的相关技巧,需要的朋友可以参考下...2020-06-25
  • php实现文件下载实例分享

    举一个案例:复制代码 代码如下:<?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常见操作,较为详细的分析并汇总了C#关于路径,文件,目录及IO常见操作,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25