PHP fopen()用法介绍(函数打开文件或URL)

2021年3月14日14:30:15 发表评论 691 次浏览

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

语法如下:

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

使用的参数:

fopen()

PHP中的function接受四个参数。

$文件

:

它是指定文件的必需参数。

$模式

:

它是必填参数, 用于指定文件或流的访问类型。

它可以具有以下可能的值:

  • " r":它表示只读。它从文件的开头开始。
  • " r +":它代表读/写, 从文件的开头开始。
  • " w":它代表只写。它将打开并清除文件的内容, 如果不存在则创建一个新文件。
  • " w +":它代表读/写。它会打开并清除文件内容, 如果不存在, 则会创建一个新文件。
  • "一种":它仅表示写入。它会打开并写入文件末尾, 如果不存在, 则会创建一个新文件。
  • " 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(所有者)。
  • 如果不确定文件名是文件还是目录, 则可能需要在调用fopen()之前使用is_dir()函数, 因为当文件名是目录时fopen()函数也可能成功。

下面的程序说明了fopen()功能。

程序1:

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

输出如下:

File does not exist!

程式2:

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

输出如下:

portal for geeks!

程式3:

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

输出如下:

portal for geeks!

计划4:

<?php 
// Opening a file using fopen() function
// in read/write mode 
$myfile = fopen ( "gfg.txt" , "w+" );
  
// writing to file
fwrite( $myfile , 'lsbin' );
  
// Setting the file pointer to 0th 
// position using rewind() function
rewind ( $myfile );
  
// writing to file on 0th position
fwrite( $myfile , 'geeksportal' );
rewind ( $myfile );
  
// displaying the contents of the file
echo fread ( $myfile , filesize ( "gfg.txt" ));
fclose( $myfile );
?>

输出如下:

geeksportalks

参考:

http://php.net/manual/en/function.fopen.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: