实现多文件上传php类

 更新时间:2016年11月25日 17:30  点击:2179
多文件上传是PHP中的一个基础应用,反正PHPer都会遇到的问题,现在就介绍一个功能完善、强大的多文件上传类给大家吧,能用上这个类的地方会很多

 代码如下 复制代码

<?php

class Upload{
 var $saveName;// 保存名
 var $savePath;// 保存路径
 var $fileFormat = array('gif','jpg','doc','application/octet-stream');// 文件格式&MIME限定
 var $overwrite = 0;// 覆盖模式
 var $maxSize = 0;// 文件最大字节
 var $ext;// 文件扩展名
 var $thumb = 0;// 是否生成缩略图
 var $thumbWidth = 130;// 缩略图宽
 var $thumbHeight = 130;// 缩略图高
 var $thumbPrefix = "_thumb_";// 缩略图前缀
 var $errno;// 错误代号
 var $returnArray= array();// 所有文件的返回信息
 var $returninfo= array();// 每个文件返回信息


// 构造函数
// @param $savePath 文件保存路径
// @param $fileFormat 文件格式限制数组
// @param $maxSize 文件最大尺寸
// @param $overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖

 function Upload($savePath, $fileFormat='',$maxSize = 0, $overwrite = 0) {
  $this->setSavepath($savePath);
  $this->setFileformat($fileFormat);
  $this->setMaxsize($maxSize);
  $this->setOverwrite($overwrite);
  $this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);
  $this->errno = 0;
 }

// 上传
// @param $fileInput 网页Form(表单)中input的名称
// @param $changeName 是否更改文件名
 function run($fileInput,$changeName = 1){
  if(isset($_FILES[$fileInput])){
   $fileArr = $_FILES[$fileInput];
   if(is_array($fileArr['name'])){//上传同文件域名称多个文件
    for($i = 0; $i < count($fileArr['name']); $i++){
     $ar['tmp_name'] = $fileArr['tmp_name'][$i];
     $ar['name'] = $fileArr['name'][$i];
     $ar['type'] = $fileArr['type'][$i];
     $ar['size'] = $fileArr['size'][$i];
     $ar['error'] = $fileArr['error'][$i];
     $this->getExt($ar['name']);//取得扩展名,赋给$this->ext,下次循环会更新
     $this->setSavename($changeName == 1 ? '' : $ar['name']);//设置保存文件名
     if($this->copyfile($ar)){
      $this->returnArray[] =  $this->returninfo;
     }else{
      $this->returninfo['error'] = $this->errmsg();
      $this->returnArray[] =  $this->returninfo;
     }
    }
    return $this->errno ?  false :  true;
   }else{//上传单个文件
    $this->getExt($fileArr['name']);//取得扩展名
    $this->setSavename($changeName == 1 ? '' : $fileArr['name']);//设置保存文件名
    if($this->copyfile($fileArr)){
     $this->returnArray[] =  $this->returninfo;
    }else{
     $this->returninfo['error'] = $this->errmsg();
     $this->returnArray[] =  $this->returninfo;
    }
    return $this->errno ?  false :  true;
   }
   return false;
  }else{
   $this->errno = 10;
   return false;
  }
 }

// 单个文件上传
// @param $fileArray 文件信息数组
 function copyfile($fileArray){
  $this->returninfo = array();
  // 返回信息
  $this->returninfo['name'] = $fileArray['name'];
  $this->returninfo['md5'] = @md5_file($fileArray['tmp_name']);
  $this->returninfo['saveName'] = $this->saveName;
  $this->returninfo['size'] = number_format( ($fileArray['size'])/1024 , 0, '.', ' ');//以KB为单位
  $this->returninfo['type'] = $fileArray['type'];
  // 检查文件格式
  if (!$this->validateFormat()){
   $this->errno = 11;
   return false;
  }
  // 检查目录是否可写
  if(!@is_writable($this->savePath)){
   $this->errno = 12;
   return false;
  }
  // 如果不允许覆盖,检查文件是否已经存在
  //if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
  // $this->errno = 13;
  // return false;
  //}
  // 如果有大小限制,检查文件是否超过限制
  if ($this->maxSize != 0 ){
   if ($fileArray["size"] > $this->maxSize){
    $this->errno = 14;
    return false;
   }
  }
  // 文件上传
  if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
   $this->errno = $fileArray["error"];
   return false;
  }elseif( $this->thumb ){// 创建缩略图
   $CreateFunction = "imagecreatefrom".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
   $SaveFunction = "image".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
   if (strtolower($CreateFunction) == "imagecreatefromgif"
    && !function_exists("imagecreatefromgif")) {
    $this->errno = 16;
    return false;
   } elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"
    && !function_exists("imagecreatefromjpeg")) {
    $this->errno = 17;
    return false;
   } elseif (!function_exists($CreateFunction)) {
    $this->errno = 18;
    return false;
   }
    
   $Original = @$CreateFunction($this->savePath.$this->saveName);
   if (!$Original) {$this->errno = 19; return false;}
   $originalHeight = ImageSY($Original);
   $originalWidth = ImageSX($Original);
   $this->returninfo['originalHeight'] = $originalHeight;
   $this->returninfo['originalWidth'] = $originalWidth;
   /*
   if (($originalHeight < $this->thumbHeight
    && $originalWidth < $this->thumbWidth)) {
    // 如果比期望的缩略图小,那只Copy
    move_uploaded_file($this->savePath.$this->saveName,
     $this->savePath.$this->thumbPrefix.$this->saveName);
   } else {
    if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度
     $thumbWidth = $this->thumbWidth ;
     $thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
     if($thumbHeight > $this->thumbHeight){// 高 > 设定高度
      $thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
      $thumbHeight = $this->thumbHeight ;
     }
    }elseif( $originalHeight > $this->thumbHeight ){// 高 > 设定高度
     $thumbHeight = $this->thumbHeight ;
     $thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );
     if($thumbWidth > $this->thumbWidth){// 宽 > 设定宽度
      $thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );
      $thumbWidth = $this->thumbWidth ;
     }
    }
    */
    $radio=max(($originalWidth/$this->thumbWidth),($originalHeight/$this->thumbHeight));
    $thumbWidth=(int)$originalWidth/$radio;
    $thumbHeight=(int)$originalHeight/$radio;

    if ($thumbWidth == 0) $thumbWidth = 1;
    if ($thumbHeight == 0) $thumbHeight = 1;
    $createdThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
    if ( !$createdThumb ) {$this->errno = 20; return false;}
    if ( !imagecopyresampled($createdThumb, $Original, 0, 0, 0, 0,
     $thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )
     {$this->errno = 21; return false;}
    if ( !$SaveFunction($createdThumb,
     $this->savePath.$this->thumbPrefix.$this->saveName) )
     {$this->errno = 22; return false;}
   
  }
  // 删除临时文件
  /*
  if(!@$this->del($fileArray["tmp_name"])){
   return false;
  }
  */
  return true;
 }

// 文件格式检查,MIME检测
 function validateFormat(){
  if(!is_array($this->fileFormat)
   || in_array(strtolower($this->ext), $this->fileFormat)
   || in_array(strtolower($this->returninfo['type']), $this->fileFormat) )
   return true;
  else
   return false;
 }
// 获取文件扩展名
// @param $fileName 上传文件的原文件名
 function getExt($fileName){
  $ext = explode(".", $fileName);
  $ext = $ext[count($ext) - 1];
  $this->ext = strtolower($ext);
 }

// 设置上传文件的最大字节限制
// @param $maxSize 文件大小(bytes) 0:表示无限制
 function setMaxsize($maxSize){
  $this->maxSize = $maxSize;
 }
// 设置文件格式限定
// @param $fileFormat 文件格式数组
 function setFileformat($fileFormat){
  if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}
 }

// 设置覆盖模式
// @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖
 function setOverwrite($overwrite){
  $this->overwrite = $overwrite;
 }


// 设置保存路径
// @param $savePath 文件保存路径:以 "/" 结尾,若没有 "/",则补上
 function setSavepath($savePath){
  $this->savePath = substr( str_replace("\","/", $savePath) , -1) == "/"
  ? $savePath : $savePath."/";
 }

// 设置缩略图
// @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高
 function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){
  $this->thumb = $thumb;
  if($thumbWidth) $this->thumbWidth = $thumbWidth;
  if($thumbHeight) $this->thumbHeight = $thumbHeight;
 }

// 设置文件保存名
// @param $saveName 保存名,如果为空,则系统自动生成一个随机的文件名
 function setSavename($saveName){
  if ($saveName == ''){  // 如果未设置文件名,则生成一个随机文件名
   $name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
   //判断文件是否存在,不允许重复文件
   if(file_exists($this->savePath . $name)){
    $name = setSavename($saveName);
    }
  } else {
   $name = $saveName;
  }
  $this->saveName = $name;
 }

// 删除文件
// @param $fileName 所要删除的文件名
 function del($fileName){
  if(!@unlink($fileName)){
   $this->errno = 15;
   return false;
  }
  return true;
 }

// 返回上传文件的信息
 function getInfo(){
  return $this->returnArray;
 }

// 得到错误信息
 function errmsg(){
  $uploadClassError = array(
   0 =>'There is no error, the file uploaded with success. ',
   1 =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
   2 =>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
   3 =>'The uploaded file was only partially uploaded. ',
   4 =>'No file was uploaded. ',
   6 =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
   7 =>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
   10 =>'Input name is not unavailable!',
   11 =>'The uploaded file is Unallowable!',
   12 =>'Directory unwritable!',
   13 =>'File exist already!',
   14 =>'File is too big!',
   15 =>'Delete file unsuccessfully!',
   16 =>'Your version of PHP does not appear to have GIF thumbnailing support.',
   17 =>'Your version of PHP does not appear to have JPEG thumbnailing support.',
   18 =>'Your version of PHP does not appear to have pictures thumbnailing support.',
   19 =>'An error occurred while attempting to copy the source image .
     Your version of php ('.phpversion().') may not have this image type support.',
   20 =>'An error occurred while attempting to create a new image.',
   21 =>'An error occurred while copying the source image to the thumbnail image.',
   22 =>'An error occurred while saving the thumbnail image to the filesystem.
     Are you sure that PHP has been configured with both read and write access on this folder?',
   );
  if ($this->errno == 0)
   return false;
  else
   return $uploadClassError[$this->errno];
 }
}

?>
如何使用这个类呢?

<?php
//如果收到表单传来的参数,则进行上传处理,否则显示表单
if(isset($_FILES['uploadinput'])){
 //建目录函数,其中参数$directoryName最后没有"/",
 //要是有的话,以'/'打散为数组的时候,最后将会出现一个空值
 function makeDirectory($directoryName) {
  $directoryName = str_replace("\","/",$directoryName);
  $dirNames = explode('/', $directoryName);
  $total = count($dirNames) ;
  $temp = '';
  for($i=0; $i<$total; $i++) {
   $temp .= $dirNames[$i].'/';
   if (!is_dir($temp)) {
    $oldmask = umask(0);
    if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
    umask($oldmask);
   }
  }
  return true;
 }

 if($_FILES['uploadinput']['name'] <> ""){
  //包含上传文件类
  require_once ('upload_class.php');
  //设置文件上传目录
  $savePath = "upload";
  //创建目录
  makeDirectory($savePath);
  //允许的文件类型
  $fileFormat = array('gif','jpg','jpge','png');
  //文件大小限制,单位: Byte,1KB = 1000 Byte
  //0 表示无限制,但受php.ini中upload_max_filesize设置影响
  $maxSize = 0;
  //覆盖原有文件吗? 0 不允许  1 允许
  $overwrite = 0;
  //初始化上传类
  $f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
  //如果想生成缩略图,则调用成员函数 $f->setThumb();
  //参数列表: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
  //$thumb=1 表示要生成缩略图,不调用时,其值为 0
  //$thumbWidth  缩略图宽,单位是像素(px),留空则使用默认值 130
  //$thumbHeight 缩略图高,单位是像素(px),留空则使用默认值 130
  $f->setThumb(1);
  
  //参数中的uploadinput是表单中上传文件输入框input的名字
  //后面的0表示不更改文件名,若为1,则由系统生成随机文件名
  if (!$f->run('uploadinput',1)){
   //通过$f->errmsg()只能得到最后一个出错的信息,
   //详细的信息在$f->getInfo()中可以得到。
   echo $f->errmsg()."<br>n";
  }
  //上传结果保存在数组returnArray中。
  echo "<pre>";
  print_r($f->getInfo());
  echo "</pre>";
 }
}else{
?>
<form enctype="multipart/form-data" action="" method="POST">
Send this file: <br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input type="submit" value="Send File"><br />
</form>
<?php
}

?>

本文章介绍了在php开发中的一些php 关闭错误提示方法,有需要的朋友可参考本文章。

一,关闭notice错误提示

1、在php.ini文件中改动error_reporting

改为:

 代码如下 复制代码

error_reporting=E_ALL & ~E_NOTICE

2、如果你不能操作php.ini文件,你可以使用如下方法

在你想禁止notice错误提示的页面中加入如下代码:

 代码如下 复制代码

error_reporting(E_ALL^E_NOTICE);

这样出现错误就不会再有任何提示了


二、关闭全部错误提示

php.ini中

打开PHP安装目录下的php.ini文件

 代码如下 复制代码

找到display_errors = On 修改为 display_errors = off

注意:如果你已经把PHP.ini文件复制到windows目录下,那么必须同时把 c:windows/php.ini里的display_errors = On 修改为display_errors = off

php程序开启
 

 代码如下 复制代码

<?php
//禁用错误报告
error_reporting(0);
//报告运行时错误
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//报告所有错误
error_reporting(E_ALL);
?>


 

在性能上关闭错误提示会给服务器性能负载加大不少哦

测试1:


在关闭错误显示的情况下,测试未初始化变量和已初始化变量在10000000次循环中的性能

变量已初始化的循环代码如下:

变量未初始化的循环代码如下:

测试成绩:


初始化:平均 5.28 秒

未初始化:平均 17.2 秒

性能差距:3.25倍


平均时间表:

我们可以看到,关闭掉PHP错误输出并不会关闭php内核对错误的处理,代码中如果有大量的Notice级别的错误,还是会降低php程序的性能。

浏览器打开页面实现文件下载的程序代码(php/jsp/java) 有需要学习的同学可参考一下。

tomcat中配置如下:

 代码如下 复制代码

    <mime-mapping>
        <extension>txt</extension>
        <mime-type>application/octet-stream</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>jpg</extension>
        <mime-type>application/octet-stream</mime-type>
    </mime-mapping>

对于如上配置,当访问扩展名txt或jpg的资源时就出现下载提示框,如果只需要对某些提到的资源让其出现下载提示框,上述配置就不行了,解决的方法是在资源的response头中设置content-type即可,例如:

php 中

 代码如下 复制代码

header("Content-type:application/octet-stream");
header('Content-Disposition: attachment; filename="downloaded.txt"');

下载文件程序

 代码如下 复制代码
<?
header("content-type:text/html; charset=utf-8");
$file_name=$_GET['name']; //服务器的真实文件名
$file_realName=urldecode($_GET['real']); //数据库的文件名urlencode编码过的
$file_dir="upload/";
$file = fopen($file_dir . $file_name,"r"); // 打开文件
// 输入文件标签
header( "Pragma: public" );
header( "Expires: 0" );
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . iconv("UTF-8","GB2312//TRANSLIT",$file_realName));
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;
?>


java 中

 代码如下 复制代码
response.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename="downloaded.txt");

如果需要为下载设置一个保存的名字,可以用Content-Disposition属性来指定。

实例

 代码如下 复制代码

<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gbk"%><%
  response.reset();//可以加也可以不加
  response.setContentType("application/x-download");//设置为下载application/x-download
  // /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
  ServletContext context = session.getServletContext();
  String realContextPath = context.getRealPath("")+"\plan\计划数据模板.xls";
  String filenamedisplay = "计划数据模板.xls";
  filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
  response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
  OutputStream output = null;
  FileInputStream fis = null;
  try
  {
  output  = response.getOutputStream();
  fis = new FileInputStream(realContextPath);
  byte[] b = new byte[1024];
  int i = 0;
  while((i = fis.read(b)) > 0)
  {
  output.write(b, 0, i);
  }
  output.flush();
  }
  catch(Exception e)
  {
  System.out.println("Error!");
  e.printStackTrace();
  }
  finally
  {
  if(fis != null)
  {
  fis.close();
  fis = null;
  }
  if(output != null)
  {
  output.close();
  output = null;
  }
  }
  %>

php中count 多维数组长度统计实现方法 有需要的朋友可参考一下下。

下面程序运行结果为()

 代码如下 复制代码

?$numb=array(
            array(10,15,30),array(10,15,30),array(10,15,30)
);
 
echo count($numb,1);

A.3
B.12
C.6
D.9

答案:B

count函数中如果mode被设置为 COUNT_RECURSIVE(或 1),则会递归底计算多维数组中的数组的元素个数(也就是你结果的12)。如果不设置mode默认为0 。不检测多维数组(数组中的数组)(结果3)。


首先遍历的是外面的数组array得出有两个元素(”color1″,”color2″,”color3″) 为3
再遍历(”color1″,”color2″,”color3″)数组得出的是9个元素 为9
结果就是3+9=12

参考

 

 代码如下 复制代码

<?php
$fruits = array (
    array (1, 2,null,null, 5, 6),
    array (1, 2,null,null, 5, 6),
);

echo(count($fruits[0]));
?>

你说的可能是用其他方式定义的数组,比如直接用:

 代码如下 复制代码

<?php
$fruits[0][0]=1;
$fruits[0][3]=1;
$fruits[0][4]=1;

echo(count($fruits[0]));
?>

这样那就输出3,因为php中的数组不要求索引必须连续,参考手册上有如下一段:

数组
PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此你可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。


实例


获得二维或多维数组的第一维的长度,这是个常用的程序判断,比如你读取的数组是一个二维数组:

 代码如下 复制代码
<?php
$arr=array(
                 0=>array('title' => '新闻1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
                 1=>array('title' => '新闻2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
                );
?>

如果你想统计数组$arr的长度,也就是说该二维数组只有两条新闻,你想要的数字也是2,但是如果使用count($arr)不同版本的php,统计的结果是不一样的;
后来在php手册中发现,count函数还有第二个参数,解释如下:
count函数有两个参数:
0(或COUNT_NORMAL)为默认,不检测多维数组(数组中的数组);
1(或COUNT_RECURSIVE)为检测多维数组,
所以如果要判断读取的数组$arr是不是有新闻信息,就要这样写了:

 代码如下 复制代码
<?php
if(is_array($arr) && count($arr,COUNT_NORMAL)>0 )
{
  .....
} else {
  .....
}
?>

你可以使用这样的代码来测试该函数:

 代码如下 复制代码
<?php
$arr=array(
                 0=>array('title' => '新闻1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
                 1=>array('title' => '新闻2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
               );
echo '不统计多维数组:'.count($arr,0);//count($arr,COUNT_NORMAL)
echo "<br/>";
echo '统计多维数组:'.count($arr,1);//count($arr,COUNT_RECURSIVE)
?>

好了,到此位置,已经解决php中获取二维或多维数组的第一维长度的问题

在php开发利用PHPMailer发送邮件是常用的做法了,这种比起php mail用好用多了,下面我们来看看PHPMailer如何发送带有附件的电子邮件吧。

.首先到http://phpmailer.worxware.com/ 下载最新版本的程序包
2.下载完成后,找到class.phpmailer.php 、class.smtp.php两个类放到自己的目录下!
3.然后新建一个php文件这里命名为:phpmail_jiucool.php
4.phpmail_jiucool.php内容如下:


实例

 代码如下 复制代码

function postmail_jiucool_com($to,$subject = "",$body = ""){
    //Author:Jiucool WebSite: http://www.jiucool.com
    //$to 表示收件人地址 $subject 表示邮件标题 $body表示邮件正文
    //error_reporting(E_ALL);
    error_reporting(E_STRICT);
    date_default_timezone_set("Asia/Shanghai");//设定时区东八区
    require_once('class.phpmailer.php');
    include("class.smtp.php");
    $mail             = new PHPMailer(); //new一个PHPMailer对象出来
    $body             = eregi_replace("[]",'',$body); //对邮件内容进行必要的过滤
    $mail->CharSet ="UTF-8";//设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
    $mail->IsSMTP(); // 设定使用SMTP服务
    $mail->SMTPDebug  = 1;                     // 启用SMTP调试功能
                                           // 1 = errors and messages
                                           // 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = "ssl";                 // 安全协议
    $mail->Host       = "smtp.googlemail.com";      // SMTP 服务器
    $mail->Port       = 465;                   // SMTP服务器的端口号
    $mail->Username   = "SMTP服务器用户名";  // SMTP服务器用户名
    $mail->Password   = "SMTP服务器密码";            // SMTP服务器密码
    $mail->SetFrom('发件人地址,如admin#jiucool.com #换成@', '发件人名称');
    $mail->AddReplyTo("邮件回复地址,如admin#jiucool.com #换成@","邮件回复人的名称");
    $mail->Subject    = $subject;
    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer! - From www.jiucool.com"; // optional, comment out and test
    $mail->MsgHTML($body);
    $address = $to;
    $mail->AddAddress($address, "收件人名称");
    //$mail->AddAttachment("images/phpmailer.gif");      // attachment
    //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
    if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!恭喜,邮件发送成功!";
        }
    }

注意:

phpmailer如果添加附件的时候,在附件名称里一定要写明附件的后缀,如果不写明附件后缀,默认的附件后缀会是.txt。
比如

 代码如下 复制代码
$mail -> AddAttachment('include/id.csv','att');//

附件的路径和附件名称
如果向上面一样添加附件发送,则最终接到的附件可能是att.txt。
AddAttachment可以设置附件编码方式和附件类型,比如上面的附件添加也可以设置为

 代码如下 复制代码
$mail -> AddAttachment('include/id.csv','att.csv',"binary","text/comma-separated-values");//

附件的路径和附件名称、
附件的编码方式大概有这么几种:支持8bit, base64, binary, and quoted-printable 编码
 
而CSV可接受的MIME Type
· application/octet-stream
· text/comma-separated-values(推荐)
· text/csv
所以,csv格式文件的附件类型可以是上面三种中的任意一种

实例

 代码如下 复制代码

require_once('include/PHPMailer/class.phpmailer.php'); //导入PHPMAILER类
$mail = new PHPMailer(); //创建实例
$mail -> CharSet='utf-8'; //设置字符集
$mail -> SetLanguage('ch','include/PHPMailer/language/');  //设置语言类型和语言文件所在目录         
$mail -> IsSMTP(); //使用SMTP方式发送
$mail -> SMTPAuth = true; //设置服务器是否需要SMTP身份验证 
$mail -> Host = SMTP_SERVER; //SMTP 主机地址 
$mail -> Port = SMTP_SERVER_PORT; //SMTP 主机端口
$mail -> From = SMTP_USER_MAIL; //发件人EMAIL地址
$mail -> FromName = 'jasonxu'; //发件人在SMTP主机中的用户名 
$mail -> Username = SMTP_USER_NAME; //发件人的姓名 
$mail -> Password = SMTP_USER_PASS; //发件人在SMTP主机中的密码 
$mail -> Subject = '测试邮件的标题'; //邮件主题 
$mail -> AltBody = 'text/html'; //设置在邮件正文不支持HTML时的备用显示
$mail -> Body = '测试邮件的内容';//邮件内容做成
$mail -> IsHTML(true);  //是否是HTML邮件
$mail -> AddAddress('chinajason2008#gmail.com','jasonxu'); //收件人的地址和姓名 
$mail -> AddReplyTo('chinajason2008#gmail.com','jasonxu'); //收件人回复时回复给的地址和姓名
$mail -> AddAttachment('include/id.csv','att.csv');//附件的路径和附件名称
if(!$mail -> Send()) //发送邮件 
var_dump($mail -> ErrorInfo);  //查看发送的错误信息


只要加上这希就可以实例邮箱发送带附件了

$mail -> AddAttachment('include/id.csv','att.csv');//附件的路径和附件名称

[!--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
  • 解决python 使用openpyxl读写大文件的坑

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

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

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 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
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • AI源文件转photoshop图像变模糊问题解决教程

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

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