php fopen()函数
定义fopen()函数打开一个文件或URL。 fopen()从C直接提起。 语法PHP fopen()函数具有以下语法。 fopen(filename,mode,include_path,context) 参数参数 是否必须 描述 filename 需要。 要打开的文件或URL mode 需要。 文件/流所需的访问类型。 include_path 可选的。 设置为“1”以在php.ini中的include_path中搜索文件 context 可选的。 文件句柄的上下文。 mode的可能值: 模式 含义 注意 "r" 只读。 在文件的开头开始 "r+" 读/写。 在文件的开头开始 "w" 只写。 打开和清除文件的内容;或创建一个新文件(如果它不存在) "w+" 读/写。 打开和清除文件的内容;或创建一个新文件(如果它不存在) "a" 只写。 打开和写入文件的末尾或创建一个新文件(如果它不存在) "a+" 读/写。 通过写入文件末尾来保存文件内容 "x" 只写。 创建新文件。返回FALSE,如果文件已存在,则返回错误 "x+" 读/写。 创建新文件。返回FALSE,如果文件已存在,则返回错误 返回值成功时返回文件指针资源,如果出错则返回FALSE。 我们可以通过在函数名前添加一个“@”来隐藏错误输出。 实例1看看下面的用法: $file1 = fopen("file.txt","r") OR die ("Can't open file!n"); $file2= fopen("$logFileName","w") OR die ("Log file not writeable!n"); fopen()函数返回文件句柄资源。您应该将fopen()的返回值存储在变量中,以供以后使用: /* http://www.manongjc.com/article/1795.html 作者:脚本之家教程 */ $filename = "c:/abc/test.txt"; $handle = fopen($filename,"a"); if (!$handle) { print "Failed to open $filename for appending.n"; } ?> 示例 - 打开远程文件fopen()可以打开远程文件。PHP自动为您打开HTTP/FTP连接,返回文件句柄。 此示例通过您的浏览器显示脚本之家教程网站: /* http://www.manongjc.com/article/1795.html 作者:脚本之家教程 */ $google = fopen("http://www.manongjc.com","r"); $site = fread($google,200000); fclose($google); print $site; ?> 指定r模式是因为Web服务器不允许通过HTTP进行写入, $file = fopen("http://www.example.com/","r"); $file = fopen("ftp://user:password@example.com/test.txt","w"); 实例2以下代码显示如何打开文件或URL。 $file = fopen("test.txt","r"); $file = fopen("test.txt","wb"); $file = fopen("http://www.example.com/","w"); /* http://www.manongjc.com/article/1795.html 作者:脚本之家教程 */ /* "r" (Read only. Starts at the beginning of the file) "r+" (Read/Write. Starts at the beginning of the file) "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist) "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist) "a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist) "a+" (Read/Write. Preserves file content by writing to the end of the file) "x" (Write only. Creates a new file. Returns FALSE and an error if file already exists) "x+" (Read/Write. Creates a new file. Returns FALSE and an error if file already exists) */ ?> 实例3以下代码显示了如何打开现有文件“test.txt”,并向其中写入一些新数据。 /* http://www.manongjc.com/article/1795.html 作者:脚本之家教程 */ $myfile = fopen("test.txt","w") or die("Unable to open file!"); $txt = "datan"; fwrite($myfile,$txt); $txt = "datan"; fwrite($myfile,$txt); fclose($myfile); ?> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
