>  기사  >  백엔드 개발  >  파일 업로드 및 다운로드의 PHP 구현

파일 업로드 및 다운로드의 PHP 구현

WBOY
WBOY원래의
2016-12-05 13:28:16930검색

이 기사에서는 PHP의 파일 업로드 및 다운로드 구현을 소개합니다. 이제 이를 공유하고 참고용으로 제공하겠습니다. 편집자를 따라가서 살펴보겠습니다.

1. 업로드 원칙 및 구성

1.1원칙

클라이언트 파일을 서버에 업로드한 후 서버 파일(임시 파일)을 지정된 디렉터리로 이동합니다.

1.2 클라이언트 구성

필수: 양식 페이지(업로드 파일 선택)

구체적으로: 전송 방법은 POST이며 enctype="multipart/form-data" 속성을 추가합니다. 둘 다 필수입니다(그러나 장점과 단점이 모두 공존하며 여기에서는 업로드 방법과 업로드된 파일 이후의 호출도 제한됩니다) ., 이에 대해서는 나중에 논의하겠습니다)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doAction.php" method="post" enctype="multipart/form-data">
请选择您要上传的文件:
<input type="file" name="myFile" /><br/>
<input type="submit" value="上传"/>
</form>
<&#63;php

&#63;>
</body>
</html>

첫 번째는 양식 페이지입니다(프론트 엔드 문제는 자동으로 무시하세요...). 핵심은 양식의 속성입니다. 다른 하나는 입력에서 type="file"을 사용하는 것입니다(강력한 속성을 반영함). PHP 확장 등).

그런 다음 doAction

<&#63;php
//$_FILES:文件上传变量
//print_r($_FILES);
$filename=$_FILES['myFile']['name'];
$type=$_FILES['myFile']['type'];
$tmp_name=$_FILES['myFile']['tmp_name'];
$size=$_FILES['myFile']['size'];
$error=$_FILES['myFile']['error'];

//将服务器上的临时文件移动到指定位置
//方法一move_upload_file($tmp_name,$destination)
//move_uploaded_file($tmp_name, "uploads/".$filename);//文件夹应提前建立好,不然报错
//方法二copy($src,$des)
//以上两个函数都是成功返回真,否则返回false
//copy($tmp_name, "copies/".$filename);
//注意,不能两个方法都对临时文件进行操作,临时文件似乎操作完就没了,我们试试反过来
copy($tmp_name, "copies/".$filename);
move_uploaded_file($tmp_name, "uploads/".$filename);
//能够实现,说明move那个函数基本上相当于剪切;copy就是copy,临时文件还在

//另外,错误信息也是不一样的,遇到错误可以查看或者直接报告给用户
if ($error==0) {
  echo "上传成功!";
}else{
  switch ($error){
    case 1:
      echo "超过了上传文件的最大值,请上传2M以下文件";
      break;
    case 2:
      echo "上传文件过多,请一次上传20个及以下文件!";
      break;
    case 3:
      echo "文件并未完全上传,请再次尝试!";
      break;
    case 4:
      echo "未选择上传文件!";
      break;
    case 5:
      echo "上传文件为0";
      break;
  }
}

먼저 print_r($_FILES) 정보를 살펴보겠습니다

Array
(
  [myFile] => Array
    (
      [name] => 梁博_简历.doc
      [type] => application/msword
      [tmp_name] => D:\wamp\tmp\php1D78.tmp
      [error] => 0
      [size] => 75776
    )

)

그래서 얻는 것은 2차원 배열입니다. 사용 방법은 모두 기본입니다(사실 저는 차원을 줄여서 사용하는 것을 좋아합니다).

기본적으로는 장황하지 않습니다. 두 가지 핵심 사항이 있습니다. tmp_name 임시 파일 이름, 오류 오류 메시지(코드 이름, 나중에 사용할 수 있음)

그런 다음 오류 정보를 사용하여 사용자에게 피드백하는 doAction의 마지막 부분을 살펴보겠습니다.

1.3 오류 보고 정보

--오류 이유:

기본적으로 파일 업로드를 위한 서버 구성을 초과하거나 준수하지 않습니다. 그렇다면 서버 측 구성은 무엇입니까?

먼저 우리가 사용한 것을 업로드해 볼까요? 게시, 업로드

php.ini에서 다음 항목을 찾으세요.

파일_업로드:켜기

upload_tmp_dir=——임시 파일 저장 디렉터리

upload_max_filesize=2M

max_file_uploads=20 - 한 번에 업로드할 수 있는 최대 파일 수(위와 차이점에 유의하세요. 크기가 있는지 없는지는 고려하지 마세요)

post_max_size=8M - 포스트 모드에서 전송되는 데이터의 최대 크기

기타 관련 구성

max_exectuion_time=-1——프로그램이 서버 리소스를 점유하지 않도록 하는 최대 실행 시간

max_input_time=60

max_input_nesting_level=64——중첩 깊이 입력

memory_limit=128M——단일 스레드의 최대 독립 메모리 사용량

간단히 말하면 자원 배분에 관한 것입니다.

--오류 번호

다음(게으른) 인용문은 http://blog.sina.com.cn/s/blog_3cdfaea201008utf.html에서 가져온 것입니다

    UPLOAD_ERR_OK 값: 0; 오류가 발생하지 않았으며 파일이 성공적으로 업로드되었습니다.
  • UPLOAD_ERR_INI_SIZE 값: 1; 업로드된 파일이 php.ini의 upload_max_filesize 옵션 제한을 초과했습니다.
  • UPLOAD_ERR_FORM_SIZE 값: 2; 업로드된 파일의 크기가 HTML 형식의 MAX_FILE_SIZE 옵션에 지정된 값을 초과합니다.
  • UPLOAD_ERR_PARTIAL 값: 3 파일의 일부만 업로드됩니다.
  • UPLOAD_ERR_NO_FILE 값: 4 업로드된 파일이 없습니다.
참고: 이 오류 메시지는 첫 번째 단계에서 업로드된 정보, 즉 임시 폴더에 업로드된 정보이며 이동이나 복사의 경우는 아닙니다.

2. 업로드 관련 제한

2.1 클라이언트 제한


<form action="doAction2.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="101321" />
업로드할 파일을 선택하세요.


<input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"/><br/>
<input type="submit" value="上传"/>
</form>
업로드된 파일의 크기와 유형을 제한하기 위해 여기에서 입력 속성이 사용되지만 개인적인 느낌은 다음과 같습니다. 첫째, html 코드가 "표시"되고, 둘째, 종종 작동하지 않습니다. 하지만 첫 번째 때문에 나도 포기하고 싶다는 것만 알아두세요

2.2 서버측 제한

주로 제한되는 것은 크기와 종류이며 그 다음으로 방법이 있습니다.


<&#63;php
header('content-type:text/html;charset=utf-8');
//接受文件,临时文件信息
$fileinfo=$_FILES["myFile"];//降维操作
$filename=$fileinfo["name"];
$tmp_name=$fileinfo["tmp_name"];
$size=$fileinfo["size"];
$error=$fileinfo["error"];
$type=$fileinfo["type"];

//服务器端设定限制
$maxsize=10485760;//10M,10*1024*1024
$allowExt=array('jpeg','jpg','png','tif');//允许上传的文件类型(拓展名
$ext=pathinfo($filename,PATHINFO_EXTENSION);//提取上传文件的拓展名

//目的信息
$path="uploads";
if (!file_exists($path)) {  //当目录不存在,就创建目录
  mkdir($path,0777,true);
  chmod($path, 0777);
}
//$destination=$path."/".$filename;
//得到唯一的文件名!防止因为文件名相同而产生覆盖
$uniName=md5(uniqid(microtime(true),true)).$ext;//md5加密,uniqid产生唯一id,microtime做前缀


if ($error==0) {
  if ($size>$maxsize) {
    exit("上传文件过大!");
  }
  if (!in_array($ext, $allowExt)) {
    exit("非法文件类型");
  }
  if (!is_uploaded_file($tmp_name)) {
    exit("上传方式有误,请使用post方式");
  }
  if (@move_uploaded_file($tmp_name, $uniName)) {//@错误抑制符,不让用户看到警告
    echo "文件".$filename."上传成功!";
  }else{
    echo "文件".$filename."上传失败!";
  }
  //判断是否为真实图片(防止伪装成图片的病毒一类的
  if (!getimagesize($tmp_name)) {//getimagesize真实返回数组,否则返回false
    exit("不是真正的图片类型");
  }

}else{
  switch ($error){
    case 1:
      echo "超过了上传文件的最大值,请上传2M以下文件";
      break;
    case 2:
      echo "上传文件过多,请一次上传20个及以下文件!";
      break;
    case 3:
      echo "文件并未完全上传,请再次尝试!";
      break;
    case 4:
      echo "未选择上传文件!";
      break;
    case 7:
      echo "没有临时文件夹";
      break;
  }
}
这里,具体实现都有注释,每一步其实都可以自己
2.3 포장

기능


<&#63;php
function uploadFile($fileInfo,$path,$allowExt,$maxSize){

$filename=$fileInfo["name"];
$tmp_name=$fileInfo["tmp_name"];
$size=$fileInfo["size"];
$error=$fileInfo["error"];
$type=$fileInfo["type"];

//服务器端设定限制

$ext=pathinfo($filename,PATHINFO_EXTENSION);

//目的信息
if (!file_exists($path)) {  
  mkdir($path,0777,true);
  chmod($path, 0777);
}
$uniName=md5(uniqid(microtime(true),true)).'.'.$ext;
$destination=$path."/".$uniName;


if ($error==0) {
  if ($size>$maxSize) {
    exit("上传文件过大!");
  }
  if (!in_array($ext, $allowExt)) {
    exit("非法文件类型");
  }
  if (!is_uploaded_file($tmp_name)) {
    exit("上传方式有误,请使用post方式");
  }
  //判断是否为真实图片(防止伪装成图片的病毒一类的
  if (!getimagesize($tmp_name)) {//getimagesize真实返回数组,否则返回false
    exit("不是真正的图片类型");
  }
  if (@move_uploaded_file($tmp_name, $destination)) {//@错误抑制符,不让用户看到警告
    echo "文件".$filename."上传成功!";
  }else{
    echo "文件".$filename."上传失败!";
  }
  

}else{
  switch ($error){
    case 1:
      echo "超过了上传文件的最大值,请上传2M以下文件";
      break;
    case 2:
      echo "上传文件过多,请一次上传20个及以下文件!";
      break;
    case 3:
      echo "文件并未完全上传,请再次尝试!";
      break;
    case 4:
      echo "未选择上传文件!";
      break;
    case 7:
      echo "没有临时文件夹";
      break;
  }
}
return $destination;
}

전화


<&#63;php
header('content-type:text/html;charset=utf-8');
$fileInfo=$_FILES["myFile"];
$maxSize=10485760;//10M,10*1024*1024
$allowExt=array('jpeg','jpg','png','tif');
$path="uploads";
include_once 'upFunc.php';
uploadFile($fileInfo, $path, $allowExt, $maxSize);

3. 여러 파일 업로드 구현

3.1 단일 파일 캡슐화 사용


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doAction5.php" method="post" enctype="multipart/form-data">
请选择您要上传的文件:<input type="file" name="myFile1" /><br/>
请选择您要上传的文件:<input type="file" name="myFile2" /><br/>
请选择您要上传的文件:<input type="file" name="myFile3" /><br/>
请选择您要上传的文件:<input type="file" name="myFile4" /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
<&#63;php
//print_r($_FILES);
header('content-type:text/html;charset=utf-8');
include_once 'upFunc.php';
foreach ($_FILES as $fileInfo){
  $file[]=uploadFile($fileInfo);
}
여기서 아이디어는 print_r($_FILES)에서 찾을 수 있습니다. 인쇄해 보면 2차원 배열이라는 것을 알 수 있습니다. 그냥 트래버스해서 사용하면 됩니다!

위 함수의 정의를 변경하고 일부 기본값을 제공하세요


function uploadFile($fileInfo,$path="uploads",$allowExt=array('jpeg','jpg','png','tif'),$maxSize=10485760){
이렇게 하면 간단하지만 몇 가지 문제가 있습니다.

정상적으로 4장의 사진을 업로드하는 것은 문제가 없으나, 중간에 해당 기능의 종료가 활성화되면 즉시 중단되어 다른 사진을 업로드할 수 없게 됩니다.

3.2 업그레이드 버전 패키지

여러 파일 또는 단일 파일 업로드를 캡슐화하는 것을 목표로 합니다

먼저 이와 같은 정적 파일을 작성하세요


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doAction5.php" method="post" enctype="multipart/form-data">
请选择您要上传的文件:<input type="file" name="myFile[]" /><br/>
请选择您要上传的文件:<input type="file" name="myFile[]" /><br/>
请选择您要上传的文件:<input type="file" name="myFile[]" /><br/>
请选择您要上传的文件:<input type="file" name="myFile[]" /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
$_FILES 인쇄


Array
(
  [myFile] => Array
    (
      [name] => Array
        (
          [0] => test32.png
          [1] => test32.png
          [2] => 333.png
          [3] => test41.png
        )

      [type] => Array
        (
          [0] => image/png
          [1] => image/png
          [2] => image/png
          [3] => image/png
        )

      [tmp_name] => Array
        (
          [0] => D:\wamp\tmp\php831C.tmp
          [1] => D:\wamp\tmp\php834C.tmp
          [2] => D:\wamp\tmp\php837C.tmp
          [3] => D:\wamp\tmp\php83BB.tmp
        )

      [error] => Array
        (
          [0] => 0
          [1] => 0
          [2] => 0
          [3] => 0
        )

      [size] => Array
        (
          [0] => 46174
          [1] => 46174
          [2] => 34196
          [3] => 38514
        )

    )

)

可以得到一个三维数组。

复杂是复杂了,但复杂的有规律,各项数值都在一起了,很方便我们取值!!

所以先得到文件信息,变成单文件处理那种信息

function getFiles(){
  $i=0;
  foreach($_FILES as $file){
    if(is_string($file['name'])){ //单文件判定
      $files[$i]=$file;
      $i++;
    }elseif(is_array($file['name'])){
      foreach($file['name'] as $key=>$val){ //我的天,这个$key用的diao
        $files[$i]['name']=$file['name'][$key];
        $files[$i]['type']=$file['type'][$key];
        $files[$i]['tmp_name']=$file['tmp_name'][$key];
        $files[$i]['error']=$file['error'][$key];
        $files[$i]['size']=$file['size'][$key];
        $i++;
      }
    }
  }
  return $files;
  
}

然后之前的那种exit错误,就把exit改一下就好了,这里用res

function uploadFile($fileInfo,$path='./uploads',$flag=true,$maxSize=1048576,$allowExt=array('jpeg','jpg','png','gif')){
  //$flag=true;
  //$allowExt=array('jpeg','jpg','gif','png');
  //$maxSize=1048576;//1M
  //判断错误号
  $res=array();
  if($fileInfo['error']===UPLOAD_ERR_OK){
    //检测上传得到小
    if($fileInfo['size']>$maxSize){
      $res['mes']=$fileInfo['name'].'上传文件过大';
    }
    $ext=getExt($fileInfo['name']);
    //检测上传文件的文件类型
    if(!in_array($ext,$allowExt)){
      $res['mes']=$fileInfo['name'].'非法文件类型';
    }
    //检测是否是真实的图片类型
    if($flag){
      if(!getimagesize($fileInfo['tmp_name'])){
        $res['mes']=$fileInfo['name'].'不是真实图片类型';
      }
    }
    //检测文件是否是通过HTTP POST上传上来的
    if(!is_uploaded_file($fileInfo['tmp_name'])){
      $res['mes']=$fileInfo['name'].'文件不是通过HTTP POST方式上传上来的';
    }
    if($res) return $res;
    //$path='./uploads';
    if(!file_exists($path)){
      mkdir($path,0777,true);
      chmod($path,0777);
    }
    $uniName=getUniName();
    $destination=$path.'/'.$uniName.'.'.$ext;
    if(!move_uploaded_file($fileInfo['tmp_name'],$destination)){
      $res['mes']=$fileInfo['name'].'文件移动失败';
    }
    $res['mes']=$fileInfo['name'].'上传成功';
    $res['dest']=$destination;
    return $res;
    
  }else{
    //匹配错误信息
    switch ($fileInfo ['error']) {
      case 1 :
        $res['mes'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
        break;
      case 2 :
        $res['mes'] = '超过了表单MAX_FILE_SIZE限制的大小';
        break;
      case 3 :
        $res['mes'] = '文件部分被上传';
        break;
      case 4 :
        $res['mes'] = '没有选择上传文件';
        break;
      case 6 :
        $res['mes'] = '没有找到临时目录';
        break;
      case 7 :
      case 8 :
        $res['mes'] = '系统错误';
        break;
    }
    return $res;
  }
}

里面封装了两个小的

function getExt($filename){
  return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}

/**
 * 产生唯一字符串
 * @return string
 */
function getUniName(){
  return md5(uniqid(microtime(true),true));
}

然后静态中,用multiple属性实现多个文件的输入;

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doAction6.php" method="POST" enctype="multipart/form-data">
请选择您要上传的文件:<input type="file" name="myFile[]" multiple='multiple' /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
doAction6
<&#63;php 
//print_r($_FILES);
header("content-type:text/html;charset=utf-8");
require_once 'upFunc2.php';
require_once 'common.func.php';
$files=getFiles();
// print_r($files);
foreach($files as $fileInfo){
  $res=uploadFile($fileInfo);
  echo $res['mes'],'<br/>';
  $uploadFiles[]=@$res['dest'];
}
$uploadFiles=array_values(array_filter($uploadFiles));
//print_r($uploadFiles);

这样子的几个文件,就实现比较强大的面向过程的上传文件的功能(学的叫一个心酸。。。);

四、面向对象的文件上传

<&#63;php 
class upload{
  protected $fileName;
  protected $maxSize;
  protected $allowMime;
  protected $allowExt;
  protected $uploadPath;
  protected $imgFlag;
  protected $fileInfo;
  protected $error;
  protected $ext;
  /**
   * @param string $fileName
   * @param string $uploadPath
   * @param string $imgFlag
   * @param number $maxSize
   * @param array $allowExt
   * @param array $allowMime
   */
  public function __construct($fileName='myFile',$uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){
    $this->fileName=$fileName;
    $this->maxSize=$maxSize;
    $this->allowMime=$allowMime;
    $this->allowExt=$allowExt;
    $this->uploadPath=$uploadPath;
    $this->imgFlag=$imgFlag;
    $this->fileInfo=$_FILES[$this->fileName];
  }
  /**
   * 检测上传文件是否出错
   * @return boolean
   */
  protected function checkError(){
    if(!is_null($this->fileInfo)){
      if($this->fileInfo['error']>0){
        switch($this->fileInfo['error']){
          case 1:
            $this->error='超过了PHP配置文件中upload_max_filesize选项的值';
            break;
          case 2:
            $this->error='超过了表单中MAX_FILE_SIZE设置的值';
            break;
          case 3:
            $this->error='文件部分被上传';
            break;
          case 4:
            $this->error='没有选择上传文件';
            break;
          case 6:
            $this->error='没有找到临时目录';
            break;
          case 7:
            $this->error='文件不可写';
            break;
          case 8:
            $this->error='由于PHP的扩展程序中断文件上传';
            break;
            
        }
        return false;
      }else{
        return true;
      }
    }else{
      $this->error='文件上传出错';
      return false;
    }
  }
  /**
   * 检测上传文件的大小
   * @return boolean
   */
  protected function checkSize(){
    if($this->fileInfo['size']>$this->maxSize){
      $this->error='上传文件过大';
      return false;
    }
    return true;
  }
  /**
   * 检测扩展名
   * @return boolean
   */
  protected function checkExt(){
    $this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION));
    if(!in_array($this->ext,$this->allowExt)){
      $this->error='不允许的扩展名';
      return false;
    }
    return true;
  }
  /**
   * 检测文件的类型
   * @return boolean
   */
  protected function checkMime(){
    if(!in_array($this->fileInfo['type'],$this->allowMime)){
      $this->error='不允许的文件类型';
      return false;
    }
    return true;
  }
  /**
   * 检测是否是真实图片
   * @return boolean
   */
  protected function checkTrueImg(){
    if($this->imgFlag){
      if(!@getimagesize($this->fileInfo['tmp_name'])){
        $this->error='不是真实图片';
        return false;
      }
      return true;
    }
  }
  /**
   * 检测是否通过HTTP POST方式上传上来的
   * @return boolean
   */
  protected function checkHTTPPost(){
    if(!is_uploaded_file($this->fileInfo['tmp_name'])){
      $this->error='文件不是通过HTTP POST方式上传上来的';
      return false;
    }
    return true;
  }
  /**
   *显示错误 
   */
  protected function showError(){
    exit('<span style="color:red">'.$this->error.'</span>');
  }
  /**
   * 检测目录不存在则创建
   */
  protected function checkUploadPath(){
    if(!file_exists($this->uploadPath)){
      mkdir($this->uploadPath,0777,true);
    }
  }
  /**
   * 产生唯一字符串
   * @return string
   */
  protected function getUniName(){
    return md5(uniqid(microtime(true),true));
  }
  /**
   * 上传文件
   * @return string
   */
  public function uploadFile(){
    if($this->checkError()&&$this->checkSize()&&$this->checkExt()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPost()){
      $this->checkUploadPath();
      $this->uniName=$this->getUniName();
      $this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext;
      if(@move_uploaded_file($this->fileInfo['tmp_name'], $this->destination)){
        return $this->destination;
      }else{
        $this->error='文件移动失败';
        $this->showError();
      }
    }else{
      $this->showError();
    }
  }
}
<&#63;php 
header('content-type:text/html;charset=utf-8');
require_once 'upload.class.php';
$upload=new upload('myFile1','imooc');
$dest=$upload->uploadFile();
echo $dest;

四、下载

对于浏览器不识别的,可以直接下载,但对于能识别的,需要多一两步

<!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>Insert title here</title>
</head>
<body>
<a href="1.rar">下载1.rar</a>
<br />
<a href="1.jpg">下载1.jpg</a>
<br />
<a href="doDownload.php&#63;filename=1.jpg">通过程序下载1.jpg</a>
<br />
<a href="doDownload.php&#63;filename=../upload/nv.jpg">下载nv.jpg</a>
<&#63;php

&#63;>
</body>
</html>
<&#63;php 
$filename=$_GET['filename'];
header('content-disposition:attachment;filename='.basename($filename));
header('content-length:'.filesize($filename));
readfile($filename);

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.