建站软件 优化软件 编程软件 网页辅助 站群程序 网站程序 图像处理 资源教程 字体下载 推荐软件


您的位置:首页 > PHP学习 > php文件上传和下载实现原理

php文件上传和下载实现原理

时间:2015-02-05 10:13:21  来源:免费模板网 作者:风雪 阅读次数 tagsphp文件上传和下载实现原理

话不多说,上代码

先来个请求页面fileupload.html


 
    
   
       
            Administration - upload new files
       
   
    
   
       

 

            Upload new news files
       
       
 
           
            Upload this file:
           
           
       
   
 


然后程序逻辑处理 php文件

 
    
   
       
            <h1> Uploading file... </h1>
<?php //Check to see if an error code was generated on the upload attempt
if ($_FILES[ 'userfile'][ 'error']>0) 
{
echo 'Problem: '; 
switch ($_FILES['userfile']['error']) {
case 1: echo 'File exceeded upload_max_filesize'; break;
case 2: echo 'File exceededmax_file_size'; break; 
case 3: echo 'File only partially uploaded'; break;
case 4: echo 'No file uploaded'; break; 
case 6: echo 'Cannot upload file: No temp directory specified.'; break; 
case 7: echo 'Upload failed: Cannotwrite to disk.'; break; 
}
exit; } // Does the file have the right MIME
    type? if ($_FILES['userfile']['type'] != 'text/plain') {
echo 'Problem: file is not plain text'; exit; } // put the file where we'd like it $upfile
    = '/uploads/'.$_FILES['userfile']['name']; if (is_uploaded_file($_FILES['userfile']['tmp_name']))
    { if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) {
    echo 'Problem: Could not move file to destination directory'; exit; } }
    else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['userfile']['name'];
    exit; } echo 'File uploaded successfully
    <br>
    <br>
    '; // reformat the file contents $fp = fopen($upfile, 'r'); $contents
    = fread ($fp, filesize ($upfile)); fclose ($fp); $contents = strip_tags($contents);
    $fp = fopen($upfile, 'w'); fwrite($fp, $contents); fclose($fp); // show
    what was uploaded echo 'Preview of uploaded file contents:<br><hr>
    '; echo $contents; echo ' <br> <hr>'; ?>
</body>
   
 



最后一步: 文件下载
 
$filePath = "template/";//此处给出你下载的文件在服务器的什么地方
$fileName = "template.xls";
//此处给出你下载的文件名
$file = fopen($filePath . $fileName, "r"); //   打开文件
//输入文件标签
Header("Content-type:application/octet-stream ");
Header("Accept-Ranges:bytes ");
Header("Accept-Length:   " . filesize($filePath . $fileName));
Header("Content-Disposition:   attachment;   filename= " . $fileName);
 
//   输出文件内容
echo fread($file, filesize($filePath . $fileName));
fclose($file);
exit;
 
?>

总的来说,上面的3个代码段只是简单介绍了php文件的上传下载,还有很多问题要解决,就例如上传大文件的时候怎么处理,批量上传、大文件下载等等问题。
当然要优化的地方很多,原理如上

 

本文地址:https://www.freemoban.com/php/2015/0205/398.html

猜你喜欢
栏目推荐
模板推荐

Copyright:www.freemoban.com 免费模板网 All Rights Reserved 网站备案:辽ICP备19014872号-2   辽公网安备 21010602000376号  辽公网安备:42900402000182号

免责声明:本站部分资源来自互联网收集,版权归原创者所有,如果侵犯了你的权益,我们会及时删除侵权内容,联系QQ:1615187561 谢谢合作!