PHP中的fopen()函数是一个内建函数,用于打开文件或URL。它用于将资源绑定到使用特定文件名的流上。要检查的文件名和模式作为参数发送到fopen()函数,如果找到匹配项,它将返回一个文件指针资源,如果失败则返回False。通过在函数名前添加’@’可以隐藏错误输出。
语法:
resource fopen ( $file, $mode, $include_path, $context)
使用的参数:
PHP中的fopen()函数接受四个参数。
file:这是一个指定文件的必需参数。mode:这是一个必需参数,指定文件的访问类型或流。
它具有以下可能的值:
返回值:
成功时返回文件指针资源,或者在错误时返回FALSE。
异常:
当向文本文件写入时,应根据平台使用正确的行结束字符。例如Unix系统使用\n,Windows系统使用\r\n,Macintosh系统使用\r作为行结束字符。
建议在用fopen()打开文件时使用‘b’标志。
如果打开失败,将生成E_WARNING级别的错误。
当安全模式启用时,PHP检查脚本所在的目录是否与正在执行的脚本具有相同的UID(所有者)。
如果您不确定filename是文件还是目录,则可能需要在调用fopen()之前使用is_dir()函数,因为fopen()函数在filename是目录时也可能成功。
以下程序说明了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!");
?>
output:
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);
?>
output
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;
?>
output:
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, 'geeksforgeeks');
// 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);
?>
output:
geeksportalks