PHP文件处理

让人想犯罪 __ 提交于 2019-12-06 11:33:22

PHP的函数支持创建,读取,上传以及编辑文件操作。常见文件操作错误有:

1.编辑错误的文件

2.被垃圾数据填满硬盘

3.意外删除文件内容

文件读取:readfile()函数:该函数读取文件,并把它写入输出缓冲。假设有一个名为webdictionary.txt的文件,放在服务器上,如下:

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

读取该文件并写入输出流的代码readfile.php如下,若读取成功则函数返回字节数:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
print("<pre>");
echo readfile("webdictionary.txt");
print("</pre>");
?>
</body>
</html>

如下,其中print("<pre>")与print("</pre>")之间的代码格式原样输出:


若只需要读取文件,用该函数就足够了。参考网址

文件打开读取:fopen(),fread(),fclose(),这个是打开文件的更好的方法,该函数可提供比readfile()函数更多的选项,这里仍然使用webdictionary.txt:

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

fopen()第一个参数包含被打开的文件名,第二个参数规定打开文件的模式,若fopen()未能打开指定文件,可自定义输出一段消息,比如以下实例:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
print("<pre>");
echo readfile("webdictionary.txt");
print("</pre>");
fclose($myfile);
?>
</body>
</html>

正常输出如上readfile()函数实例一致,若无法找到文件:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("webdictionary1.txt", "r") or die("Unable to open file!");
print("<pre>");
echo readfile("webdictionary.txt");
print("</pre>");
fclose($myfile);
?>
</body>
</html>

则输出如下,此处没有屏蔽警告消息,警告消息屏蔽可在前面添加语句ini_set("error_reporting","E_ALL & ~E_NOTICE")实现


文件会以如下模式之一打开:

模式描述
r打开文件为只读,文件指针在文件的开头开始。
w打开文件为只写,若它不存在,删除文件的内容或创建一个新的文件。文件指针在文件的开头开始。
a打开文件为只写,文件中的现有数据会被保留,文件指针在文件结尾开始,若文件不存在,创建新的文件
x创建新文件为只写,若文件存在,则返回FALSE和错误
r+打开文件为读/写,文件指针在文件开头开始
w+打开文件为读/写,若文件不存在,删除文件内容或创建新文件,文件指针在文件开头开始
a+打开文件为读/写,文件中已有数据会被保留,文件指针在文件结尾开始,若它不存在,则创建新文件
x+创建新文件为读/写,若文件已存在,则返回FALSE和错误

读取文件fread():

它读取打开的文件,它的第一个参数包含待读取文件的文件名,第二个参数规定待读取的最大字节数。

如下php代码把webdictionary.txt文件读至结尾:

fread($myfile,filesize("webdictinary.txt"))

关闭文件fclose():

它关闭打开的文件,用完文件后把它们全部关闭是一个良好的变成习惯,因为没有人想打开的文件占用服务器资源,fclose()需要待关闭文件的名称,或存有文件名的变量:

<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
读取单行文件-fgets():

用于从文件读取单行,下面输出webdictionary.txt文件的首行,调用fgets()函数后,文件指针会移动到下一行:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
print("<pre>");
echo readfile("webdictionary.txt");
print("</pre>");
echo fgets($myfile);
fclose($myfile);
?>
</body>
</html>

如下:


检查End-Of-File - feof():

feof()函数检查是否已到达"end-of-file"(EOF),对遍历未知长度的数据很有用,下面逐行读取webdictionary.txt文件,直到end-of-file:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
#print("<pre>");
#echo readfile("webdictionary.txt");
#print("</pre>");
//输出单行直到end-of-file
while(!feof($myfile)){
   echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
</body>
</html>

如下:


读取单字符-fgetc():

该函数从文件中读取单个字符,下面逐字从文件webdictionary.txt文件中读取字符,直到eof:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
#print("<pre>");
#echo readfile("webdictionary.txt");
#print("</pre>");
//输出单行直到end-of-file
#while(!feof($myfile)){
 #  echo fgets($myfile) . "<br>";
#}
while(!feof($myfile)){
   echo fgetc($myfile);
}
fclose($myfile);
?>
</body>
</html>

在调用fgetc()函数之后,文件指针会移到下一个字符。

参考网址

文件创建和写入:

fopen()创建文件,它与打开文件函数是一样的,若用fopen()打开并不存在的文件,且打开模式设置为写入w或附加a,则此函数会创建一个新文件,下面实例创建名为testfile.txt的新文件,此文件会被创建于与PHP代码所在目录相同的位置:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("testfile.txt", "w");
?>
</body>
</html>


若运行此代码时发生错误,则检查是否有向硬盘写入信息的php文件访问权限。

fwrite()函数用于写入文件,它的第一个参数为要写入的文件名,第二个参数为被写入的字符串。

下面把姓名写入文件名为newfile.txt的新文件中:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("newfile.txt", "w") or die("unable to open file!");
$txt = "Bill Gates\n";
fwrite($myfile,$txt);
$txt = "Putao Stanway";
fwrite($myfile, $txt);
fclose($myfile);
?>
</body>
</html>

如下:



这里写入两次,第一次写入Bill Gates,第二次写入Putao Stanway,写完后,使用fclose()来关闭文件。

覆盖旧数据:

若newfile.txt包含了一些数据,则在写入已有文件时,已存在的数据会被擦除并以一个新文件开始,下面实例就是打开一个已存在文件newfile.txt,并向其中写入一些新数据:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$myfile = fopen("newfile.txt", "w") or die("unable to open file!");
$txt = "Tom Cat\n";
fwrite($myfile,$txt);
$txt = "Mickey Mouse";
fwrite($myfile, $txt);
fclose($myfile);
?>
</body>
</html>


文件上传:

1.创建一个文件上传表单:

允许用户从表单上传文件非常有用,如下就是一个供上传文件的HTML表单,文件upload_form.html:

<html>
<head>
<meta charset="utf-8">
</head>
<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">文件名: </label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="提交" />
</form>

</body>
</html>

这里注意<form>标签内的enctype属性规定了在提交表单时要使用哪种内容类型,在表单需要二进制数据时,比如文件内容,需使用"multipart/form-data"。

<input>标签的type="file"属性规定了应该把输入作为文件来处理,比如,当浏览器中预览时,会看到输入框旁边有一个浏览按钮。

注意允许用户上传文件是一个巨大的安全风险,需仅允许可信的用户执行文件上传操作。

创建上传脚本:

upload_file.php:其中含供上传文件的代码

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>


</body>
</html>

通过PHP的全局数组$_FILES,可从客户计算机向远程服务器上传文件。

第一个参数是表单的input name,第二个下标可以是name,type,size,tmp_name或error,如下所示:

1.$_FILES["file"]["name"] - 被上传文件的名称

2.$_FILES["file"]["type"] - 被上传文件的类型

3.$_FILES["file"]["size"] - 被上传文件大小,以字节为单位

4.$_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本名称

5.$_FILES["file"]["error"] - 由文件上传导致的错误代码

这是一种非常简单的文件上传方式,基于安全方面考虑,应该增加有关什么用户有权上传文件的限制。

上面的临时副本在脚本结束时就会消失。


上传限制:这里增加对上传文件的限制,用户只能上传.gif或.jpeg文件,文件大小必须小于20KB:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
  ini_set("error_reporting","E_ALL & ~E_NOTICE");
  if ((($_FILE["file"]["type"] == "image/gif")
  || ($_FILE["file"]["type"] == "image/jpeg")
  || ($_FILE["file"]["type"] == "image/pjpeg"))
  && ($_FILE["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
  {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
  else
     {
      echo "Upload: " . $_FILES["file"]["name"] . "<br />";
      echo "Type: " . $_FILES["file"]["type"] . "<br />";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
     }
  }
  else
  {
    echo "Invalid file";
  }
?>

</body>
</html>

保存被上传文件:上面的例子在服务器的php临时文件夹创建了一个被上传文件的临时副本,这个临时的复制文件会在脚本结束时效实,要保存被上传文件,需要把它拷贝到另外的位置,这里把它拷贝到当前目录下的upload目录下:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
  #ini_set("error_reporting","E_ALL & ~E_NOTICE");
  if ((($_FILES["file"]["type"] == "image/gif")
  || ($_FILES["file"]["type"] == "image/jpeg")
  || ($_FILES["file"]["type"] == "image/pjpeg"))
  && ($_FILES["file"]["size"] < 204800))
  {
  if ($_FILES["file"]["error"] > 0)
  {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
  else
     {
      echo "Upload: " . $_FILES["file"]["name"] . "<br />";
      echo "Type: " . $_FILES["file"]["type"] . "<br />";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
     
	  if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
	    echo $_FILES["file"]["name"] . " already exists. ";
	  }
	  else
		 {
	        move_uploaded_file($_FILES["file"]["tmp_name"],
				"upload/" . $_FILES["file"]["name"]);
			echo " Stored in: " . "upload/" . $_FILES["file"]["name"];
	     }
	 }
  }
  else
  {
    echo "Invalid file";
  }
?>

</body>
</html>

上面还检测了一下此文件是否存在,若不存在则把文件拷贝到指定目录upload下。



参考网址

















易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!