php implementation file download of supports Chinese names
- 2020-12-05 17:08:30
- OfStack
/*======================================================
$FileName File name , Will pass
$FilePath Is the file path . optional , It can be a relative path or an absolute path
A path can only consist of English and data , No Chinese
======================================================*/
<?php
header("Content-type: text/html;charset=utf-8");
if(strlen($FileName)<=3){echo " Failed download: You downloaded the wrong file ";return;}
$FileName=iconv("utf-8","gb2312",$FileName);// Do file name format conversion , In case Chinese is confused
// Start judging the path
if(!is_null($FilePath)&&strlen($FilePath)>1){
if(substr($FilePath,0,1)=='/'){// Determine if it is an absolute path
$FilePath=$_SERVER['DOCUMENT_ROOT'].$FilePath;
}
if(substr($FilePath,-1)!="/"){// Check to see if it is / At the end
$FilePath=$FilePath.'/';
}
if(is_numeric(strpos($FilePath,":\"))){// Check if it is an absolute path
$FilePath=str_replace("/","\",$FilePath);
}
}elseif(strlen($FilePath)==1&&$FilePath!="/"){
$FilePath=$FilePath."/";
}else{
$FilePath="";
}
if(!file_exists($FilePath.$FileName)){
echo" Download failed: The file to be downloaded was not found ";return;
}
/*================================================
Send the header information associated with the download
=================================================*/
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");// Returns in bytes
header("Accept-Length: $FileSize");// Return file size
header("Content-Disposition: attachment; filename=".$FileName);// Here the client side pops up a dialog box with the corresponding file name
/*================================================
Start downloading related
=================================================*/
$FileSize=filesize($FilePath.$FileName);
$File=fopen($FilePath.$FileName,"r");// Open the file
$FileBuff=512;
while($FileSize>=0){
$FileSize-=$FileBuff;
echo fread($File,$FileBuff);
}
fclose($File);
}
?>