search
Homephp教程php手册[PHP]进阶教程:PHP中的文件打开、关闭与文件上传案例教程

打开文件 fopen() 函数用于在 PHP 中打开文件。 此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件: htmlbody?php$file=fopen(welcome.txt,r);?/body/html 文件可能通过下列模式来打开: r:只读。在文件的开头开始。 r:

打开文件
fopen() 函数用于在 PHP 中打开文件。
此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:


<?php $file=fopen("welcome.txt","r");
?>



文件可能通过下列模式来打开:
r:只读。在文件的开头开始。
r+:读/写。在文件的开头开始。
w:只写。打开并清空文件的内容;如果文件不存在,则创建新文件。
w+:读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。
a:追加。打开并向文件文件的末端进行写操作,如果文件不存在,则创建新文件。
a+:读/追加。通过向文件末端写内容,来保持文件内容。
x:只写。创建新文件。如果文件已存在,则返回 FALSE。
x+:读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。

注释:如果 fopen() 无法打开指定文件,则返回 0 (false)。


例子

如果 fopen() 不能打开指定的文件,下面的例子会生成一段消息:


<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>



关闭文件
fclose() 函数用于关闭打开的文件。

<?php $file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>


检测 End-of-file
feof() 函数检测是否已达到文件的末端 (EOF)。
在循环遍历未知长度的数据时,feof() 函数很有用。
注释:在 w 、a 以及 x 模式,您无法读取打开的文件!

if (feof($file)) echo "End of file";

逐行读取文件
fgets() 函数用于从文件中逐行读取文件。
注释:在调用该函数之后,文件指针会移动到下一行。
例子
下面的例子逐行读取文件,直到文件末端为止:
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>
[PHP]进阶教程:PHP中的文件打开、关闭与文件上传案例教程


逐字符读取文件

fgetc() 函数用于从文件逐字符地读取文件。
注释:在调用该函数之后,文件指针会移动到下一个字符。
例子
下面的例子逐字符地读取文件,直到文件末端为止:

<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?>

上传文件主要是以下几步:

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

允许用户从表单上传文件是非常有用的。
请看下面这个供上传文件的 HTML 表单:




在表单需要二进制数据时,比如文件内容,请使用 "multipart/form-data"。

举例来说,当在浏览器中预览时,会看到输入框旁边有一个浏览按钮。

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

效果如图所示:

[PHP]进阶教程:PHP中的文件打开、关闭与文件上传案例教程



2.创建上传脚本
"upload_file.php" 文件含有供上传文件的代码:

<?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"];
  }
?>

效果如图所示:

[PHP]进阶教程:PHP中的文件打开、关闭与文件上传案例教程

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

第一个参数是表单的 input name,第二个下标可以是 "name", "type", "size", "tmp_name" 或 "error"。就像这样:

  • $_FILES["file"]["name"] - 被上传文件的名称
  • $_FILES["file"]["type"] - 被上传文件的类型
  • $_FILES["file"]["size"] - 被上传文件的大小,以字节计
  • $_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称
  • $_FILES["file"]["error"] - 由文件上传导致的错误代码

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

这里的$_FILES是一个多维数组。第一维是files文件的数组,因为表单中的input的name(不是id或者其他)是file。第二则是每个文件的相关数据,包含了上面列出的种种属性。



上传限制

在这个脚本中,我们增加了对文件上传的限制。用户只能上传 .gif 或 .jpeg 文件,文件大小必须小于 20 kb:

<?php if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["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";
  }

?>
注释:对于 IE,识别 jpg 文件的类型必须是 pjpeg,对于 FireFox,必须是 jpeg。



保存被上传的文件

上面的例子在服务器的 PHP 临时文件夹创建了一个被上传文件的临时副本。
这个临时的复制文件会在脚本结束时消失。要保存被上传的文件,我们需要把它拷贝到另外的位置:

<?php if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    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";
  }
?>
上面的脚本检测了是否已存在此文件,如果不存在,则把文件拷贝到指定的文件夹。

注释:这个例子把文件保存到了名为 "upload" 的新文件夹,该文件夹要存在,如果没有需要新建。

move_uploaded_file(file,newloc) 函数将上传的文件移动到新位置。

若成功,则返回 true,否则返回 false。

file 必需----规定要移动的文件。newloc 必需----规定文件的新位置。

在使用move_uploaded_file()函数时可能会遇类似如下错误:
Warning: move_uploaded_file(/dest/inat/ion.ext) [function.move-uploaded-file]: failed to open stream: No such file or directory in /upload/handler.php on line X
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/temp/file/name' to '/dest/inat/ion.ext' in /upload/handler.php on line X
一般不是 '/temp/file/name'...的错误,而可能是路径'/dest/inat' 不存在. 如果真是这样只要创建这个路径,问题就解决了。

我还遇到这样一个情况,路径是正确的,但是用的是访问路径,而不是内部的文件操作路径导致文件无法写入。

还有就是要注意写入的路径开头的部分不要再加“\”,如将“’uploads\’.$_FILES['userfile']['name']”写成“’\uploads\’.$_FILES['userfile']['name']”。

总之,最先要检查的就是要写入的路径,问题很有可能出在这里。

但是即使如此,还是报错了:
Warning: move_uploaded_file(upload/12.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied inupload_file.php on line24

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/saetmp/928/xququer/1359821561_2429732845/phppSXyZ6' to 'upload/12.jpg' inupload_file.php on line24

这是一般是没有权限读写文件夹的问题。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)