上传文件函数的运用

程序来自:PHP与MySQL.WEB开发第三版,最近一直在看这个,我觉得下面的两个程序对学习文件上传很有帮助,现在对他进行一下自已理解的解释。

upload.htm

<html>
<head>
<title>Administration - upload new files</title> 
</head> 
<body>
<h1>Upload new news files</h1>

<!--上传文件好像一定这种格式的-->
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Upload this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
</body>
</html>

 

upload.php

 

<html>
<head>
  <title>Uploading...</title>
</head>
<body>
<h1>Uploading file...</h1>
<?php

//判断错误的类型

  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;
    }
    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'];

 

// 判断文件是否是通过 HTTP POST 上传的所以在upload.html处method一定要post


  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
  $contents = fread ($fp, filesize ($upfile));
  fclose ($fp);
 //对$contents进行设置
  $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>
</html>
好了解释就差不多了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值