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">提交</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.读上传的文档

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);//kill empty
return $data;
}
$name = 'load.txt';
$data = readData($name);
print_r($data);

2.2一次性读完,返回到一个string,这个string的分隔符是\r\n

$alldata = file_get_contents('upload'.'/'.$name);
$onedata = explode("\r\n",$alldata);
print_r($alldata);
echo "<br/>";
print_r($onedata);

2.3有中文等特殊字符

/*逐行读取TXT文件*/
function getTxtcontent($txtfile){
$file = @fopen($txtfile,'r');
$content = array();
if(!$file){
return 'file open fail';
}else{
$i = 0;
while (!feof($file)){
$content[$i] = mb_convert_encoding(fgets($file),"UTF-8","GBK,ASCII,ANSI,UTF-8");
$i++ ;
}
fclose($file);
$content = array_filter($content); //数组去空
}
return $content;
}

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.删除指定文件

$file = "upload/load.txt";
if (!unlink($file))
echo ("Error deleting $file");
}else{
echo ("Deleted $file");
}