1.创建目录如下
upload文件夹是用来暂时存放上传的文件,方便读取和写等操作,upload.html是前端上传文件页面,upload.php是处理页面
upload.html
<html> <form action="upload.php" method="POST" enctype="multipart/form-data"> <label>选择文件</label> <input type="file" id="file" name="file" /> <button type="submit" class="btn btn-primary">提交</button> </form> </html>
upload.php
<?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { $fileName = $_FILES["file"]["name"]; $type = $_FILES["file"]["type"]; $size = ($_FILES["file"]["size"] / 1024)." kb" ; $tmp_name = $_FILES["file"]["tmp_name"] ; echo "Upload: " .$fileName . "<br />"; echo "Type: " . $tyep . "<br />"; echo "Size: " . $size. " Kb<br />"; echo "Stored in: " . $tmp_name."<br />"; move_uploaded_file($tmp_name,"upload/" .$fileName); echo "success"; } ?>
结果如下:
上传文件
结果
-----------------------------------------------------------------------------
2.下面对上传的文件进行读操作
1)逐行读
function readData($name){ if($name=='')return ''; $file = fopen(upload.'/'.$name, "r"); $data=array(); $i=0; //输出文本中所有的行,直到文件结束为止。 while(! feof($file)) { $data[$i]= fgets($file);//fgets()函数从文件指针中读取一行 $i++; } fclose($file); $data=array_filter($data); return $data; } $name = 'load.txt'; $data = readData($name); print_r($data);
2)一次性读完,返回到一个string,这个string的分隔符是
$alldata = file_get_contents('upload'.'/'.$name); $onedata = explode(" ",$alldata); print_r($alldata); echo "<br/>"; print_r($onedata);
---------------------------------------------------------------------
3.删除一个文件夹下面的所有文件
public static function delFile($dirName){ if(file_exists($dirName) && $handle=opendir($dirName)){ while(false!==($item = readdir($handle))){ if($item!= "." && $item != ".."){ if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){ delFile($dirName.'/'.$item); }else{ if(unlink($dirName.'/'.$item)){ return true; } } } } closedir( $handle); } }
4.删除指定文件
<?php $file = "upload/load.txt"; if (!unlink($file)) { echo ("Error deleting $file"); } else { echo ("Deleted $file"); } ?>