使用php上传文件

参考: http://www.phpchina.com/html/97/14397-4443.html

 

 

利用html提供的文件上传功能,php其实仅仅是把它保存在本地指定目录。

 

1、首先dump php 内置变量:

 

#var_dump($_FILES);

array(1) {
["file"]=>
array(5) {
["name"]=>
string(8) "test.txt"
["type"]=>
string(10) "text/plain"
["tmp_name"]=>
string(18) "/var/tmp/phpUCf72l"
["error"]=>
int(0)
["size"]=>
int(589)
}
}

可以看到文件其实已经被临时存放在服务器了。

 

2、这时需要做的,就是把它用合适的名称保存到指定目录。

获取文件后缀,进行一些必要的检查。

生成一个唯一的文件名。

 

---------------------------------------------

# index.html

<form method="post" action="upload.php" enctype="multipart/form-data">
       <table border=0 cellspacing=0 cellpadding=0 align=center width="100%">
        <tr>
          <td width=55 height=20 align="center"><input type="hidden" name="MAX_FILE_SIZE" value="2000000">文件: </TD>
          <td height="16">
          <input name="file" type="file"  value="浏览" >
          
          <input type="submit" value="上传" name="B1">
          </td>
        </tr>
       </table>
       </form>

 

# upload.php

 

 <?php
  //var_dump($_FILES);
 
  $uploaddir = "./files/";//设置文件保存目录 注意包含/  
  $allow_types = array("txt");//设置允许上传文件的类型
 
  // 返回函数
+ +--  4 lines: function _return($ret_code, $ret_msg){------------------------------------------------------------------------------
+ +--  3 lines: function _return_ok($ret_msg){--------------------------------------------------------------------------------------
+ +--  3 lines: function _return_error($ret_msg){-----------------------------------------------------------------------------------
 
  // 原始文件信息
  $raw_file_name = trim($_FILES['file']['name']);
  $raw_file_type = trim($_FILES['file']['type']);
  $raw_file_tail = strtolower(substr(strrchr($raw_file_name, '.'), 1));
 
  //判断文件类型
  if(!in_array($raw_file_tail, $allow_types)){
      $text = implode(",",$allow_types);
      _return_error("allow type: $text");
  }
  if ('text/plain' != $raw_file_type){
      _return_error("allow type: text/plain");
  } 
 
  //生成目标文件的文件名  
  $upload_file_name = tempnam($uploaddir, $raw_file_name.".");
 
  // 保存文件
  if (move_uploaded_file($_FILES['file']['tmp_name'],$upload_file_name)){
      _return_ok("ok");
  } else {
      _return_error("fail");
  }  
  exit;
  ?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值