当前位置:  首页>> 技术小册>> PHP合辑2-高级进阶

PHP中的fopen()函数是一个内建函数,用于打开文件或URL。它用于将资源绑定到使用特定文件名的流上。要检查的文件名和模式作为参数发送到fopen()函数,如果找到匹配项,它将返回一个文件指针资源,如果失败则返回False。通过在函数名前添加’@’可以隐藏错误输出。

语法:

  1. resource fopen ( $file, $mode, $include_path, $context)

使用的参数:

PHP中的fopen()函数接受四个参数。

file:这是一个指定文件的必需参数。mode:这是一个必需参数,指定文件的访问类型或流。
它具有以下可能的值:

  • “r”:它代表只读。它从文件的开头开始。
  • “r+”:它代表读写。它从文件的开头开始。
  • “w”:它代表只写。它打开文件并清除其内容,或者在没有该文件的情况下创建一个新文件。
  • “w+”:它代表读写。它打开文件并清除其内容,或者在没有该文件的情况下创建一个新文件。
  • “a”:它代表只写。它打开并在文件的末尾写入或者在没有该文件的情况下创建一个新文件。
  • “a+”:它代表读写。它将写入文件末尾以保留文件内容。
  • “x”:它代表只写。它创建一个新文件,并在文件已经存在时返回FALSE和错误信息。
  • “x+”:它代表读写。它创建一个新文件,并在文件已经存在时返回FALSE和错误信息。
  • $include_path:这是一个可选参数,当您希望在include_path中(例如php.ini)搜索文件时,该参数设置为1。
  • $context:这是一个可选参数,用于设置流的行为。

返回值:

成功时返回文件指针资源,或者在错误时返回FALSE。

异常:

当向文本文件写入时,应根据平台使用正确的行结束字符。例如Unix系统使用\n,Windows系统使用\r\n,Macintosh系统使用\r作为行结束字符。

建议在用fopen()打开文件时使用‘b’标志。

如果打开失败,将生成E_WARNING级别的错误。

当安全模式启用时,PHP检查脚本所在的目录是否与正在执行的脚本具有相同的UID(所有者)。

如果您不确定filename是文件还是目录,则可能需要在调用fopen()之前使用is_dir()函数,因为fopen()函数在filename是目录时也可能成功。

以下程序说明了fopen()函数。
示例1

  1. <?php
  2. // Opening a file using fopen()
  3. // function in read only mode
  4. $myfile = fopen("/home/geeks/gfg.txt", "r")
  5. or die("File does not exist!");
  6. ?>

output:

  1. File does not exist!

示例2

  1. <?php
  2. // Opening a file using fopen()
  3. // function in read/write mode
  4. $myfile = fopen("gfg.txt", 'r+')
  5. or die("File does not exist!");
  6. $pointer = fgets($myfile);
  7. echo $pointer;
  8. fclose($myfile);
  9. ?>

output

  1. portal for geeks!

示例3

  1. <?php
  2. // Opening a file using fopen() function
  3. // in read mode along with b flag
  4. $myfile = fopen("gfg.txt", "rb");
  5. $contents = fread($myfile, filesize($myfile));
  6. fclose($myfile);
  7. print $contents;
  8. ?>

output:

  1. portal for geeks!

示例4

  1. <?php
  2. // Opening a file using fopen() function
  3. // in read/write mode
  4. $myfile = fopen("gfg.txt", "w+");
  5. // writing to file
  6. fwrite($myfile, 'geeksforgeeks');
  7. // Setting the file pointer to 0th
  8. // position using rewind() function
  9. rewind($myfile);
  10. // writing to file on 0th position
  11. fwrite($myfile, 'geeksportal');
  12. rewind($myfile);
  13. // displaying the contents of the file
  14. echo fread($myfile, filesize("gfg.txt"));
  15. fclose($myfile);
  16. ?>

output:

  1. geeksportalks