• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php文件下传、上载

php 搞代码 3年前 (2022-01-23) 21次浏览 已收录 0个评论

php文件上传、下载

以前一直在做java,最近转行去搞php开发,总觉得力不从心。这几天有个需求,是关于php的文件上传和下载的。给大家分享下自己的学习资料。

?

1.先来个请求页面upload.html

  <title>Administration - upload new files</title><body><h1>Upload new news files</h1>    Upload this file:   

?

2.php处理客户端请求的数据upload.html

  <title>Uploading...</title><body><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 exceeded max_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: Cannot write 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>';?>

?

3.php文件下载

<?php	$filePath = "template/";//此处给出你下载的文件在服务器的什么地方	$fileName = "template.xls";	//此处给出你下载的文件名	$file = fopen($filePath . $fileName, "r"); //   打开文件	//输入文件标签	Header("Content-type:application/octet-stream ");	Header("Acce<em style="color:transparent">本文来源[email protected]搞@^&代*@码)网9</em><strong>搞代gaodaima码</strong>pt-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文件的上传下载,还有很多问题要解决,就例如上传大文件的时候怎么处理,批量上传、大文件下载等等问题。当然跟java一样,php也有很多框架可以解决这方面。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php文件下传、上载

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址