百科狗-知识改变命运!
--

fopen() - 打开文件或者 URL - php 文件目录函数

乐乐1年前 (2023-11-21)阅读数 22#技术干货
文章标签文件

fopen()

(PHP 4, PHP 5, PHP 7)

打开文件或者 URL

说明

fopen(string $filename,string $mode[,bool $use_include_path= false[,resource $context]]): resource

fopen()将$filename指定的名字资源绑定到一个流上。

参数

$filename

如果$filename是"scheme://..."的格式,则被当成一个 URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将$filename当成一个普通的文件名继续执行下去。

如果 PHP 认为$filename指定的是一个本地文件,将尝试在该文件上打开一个流。该文件必须是 PHP 可以访问的,因此需要确认文件访问权限允许该访问。如果激活了安全模式或者open_basedir则会应用进一步的限制。

如果 PHP 认为$filename指定的是一个已注册的协议,而该协议被注册为一个网络 URL,PHP 将检查并确认allow_url_fopen已被激活。如果关闭了,PHP 将发出一个警告,而 fopen 的调用则失败。

Note:

所支持的协议列表见支持的协议和封装协议。某些协议(也被称为wrappers)支持context和/或php.ini选项。参见相应的页面哪些选项可以被设定(例如php.ini中用于httpwrapper 的user_agent值)。

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

$mode

$mode参数指定了所要求到该流的访问类型。可以是以下:

fopen()中$mode的可能值列表
$mode说明
'r'只读方式打开,将文件指针指向文件头。
'r+'读写方式打开,将文件指针指向文件头。
'w'写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'w+'读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'a'写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'a+'读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'x'创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则fopen()调用失败并返回FALSE,并生成一条E_WARNING级别的错误信息。如果文件不存在则尝试创建之。这和给底层的open(2)系统调用指定O_EXCL|O_CREAT标记是等价的。
'x+'创建并以读写方式打开,其他的行为和'x'一样。
'c'Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to'w'), nor the call to this function fails (as is the case with'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (seeflock()) before attempting to modify the file, as using'w'could truncate the file before the lock was obtained (if truncation is desired,ftruncate()can be used after the lock is requested).
'c+'Open the file for reading and writing; otherwise it has the same behavior as'c'.
Note:

不同的操作系统家族具有不同的行结束习惯。当写入一个文本文件并想插入一个新行时,需要使用符合操作系统的行结束符号。基于 Unix 的系统使用n作为行结束字符,基于 Windows 的系统使用rn作为行结束字符,基于 Macintosh 的系统使用r作为行结束字符。

如果写入文件时使用了错误的行结束符号,则其它应用程序打开这些文件时可能会表现得很怪异。

Windows 下提供了一个文本转换标记('t')可以透明地将n转换为rn。与此对应还可以使用'b'来强制使用二进制模式,这样就不会转换数据。要使用这些标记,要么用'b'或者用't'作为$mode参数的最后一个字符。

默认的转换模式依赖于 SAPI 和所使用的 PHP 版本,因此为了便于移植鼓励总是指定恰当的标记。如果是操作纯文本文件并在脚本中使用了n作为行结束符,但还要期望这些文件可以被其它应用程序例如 Notepad 读取,则在 mode 中使用't'。在所有其它情况下使用'b'

在操作二进制文件时如果没有指定'b'标记,可能会碰到一些奇怪的问题,包括坏掉的图片文件以及关于rn字符的奇怪问题。Note:

为移植性考虑,强烈建议在用fopen()打开文件时总是使用'b'标记。Note:

fopen() - 打开文件或者 URL - php 文件目录函数

再一次,为移植性考虑,强烈建议你重写那些依赖于't'模式的代码使其使用正确的行结束符并改成'b'模式。$use_include_path

如果也需要在include_path中搜寻文件的话,可以将可选的第三个参数$use_include_path设为'1'或TRUE

$contextNote:在 PHP 5.0.0中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见Streams。

返回值

成功时返回文件指针资源,如果打开失败,本函数返回FALSE

错误/异常

如果打开失败,会产生一个E_WARNING错误。可以通过@来屏蔽错误。

更新日志

版本说明
4.3.2自 PHP 4.3.2 起,对所有区别二进制和文本模式的平台默认模式都被设为二进制模式。如果在升级后脚本碰到问题,尝试暂时使用't'标记,直到所有的脚本都照以下所说的改为更具移植性以后。
4.3.2增加了选项'x''x+'
5.2.6增加了选项'c''c+'

范例

Example #1fopen()例子

注释

Warning

使用 SSL 时,Microsoft IIS会违反协议不发送close_notify标记就关闭连接。PHP 会在到达数据尾端时报告“SSL: Fatal Protocol Error”。要解决此问题,error_reporting应设定为降低级别至不包含警告。PHP 4.3.7 及更高版本可以在使用https://包装器打开流时检测出有问题的 IIS 服务器软件并抑制警告。在使用fsockopen()创建ssl://套接字时,开发者需检测并抑制此警告。

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

Note:

如果在用服务器模块版本的 PHP 时在打开和写入文件上遇到问题,记住要确保所使用的文件和目录是服务器进程所能够访问的。Note:

This function may also succeed when$filenameis a directory. If you are unsure whether$filenameis a file or a directory, you may need to use theis_dir()function before callingfopen().

参见

  • 支持的协议和封装协议
  • fclose() 关闭一个已打开的文件指针
  • fgets() 从文件指针中读取一行
  • fread() 读取文件(可安全用于二进制文件)
  • fwrite() 写入文件(可安全用于二进制文件)
  • fsockopen() 打开一个网络连接或者一个Unix套接字连接
  • file() 把整个文件读入一个数组中
  • file_exists() 检查文件或目录是否存在
  • is_readable() 判断给定文件名是否可读
  • stream_set_timeout()Set timeout period on a stream
  • popen() 打开进程文件指针
  • stream_context_create() 创建资源流上下文
  • umask() 改变当前的 umask
  • SplFileObject
Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair.
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.
i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:
ftp://blossom:buttercup@example.com//var/school/bubbles.txt
Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.
Note that whether you may open directories is operating system dependent. The following lines:

demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.
On UNIX, you may happily read the directory format for the native filesystem.
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts. 
make a loader file contents by code
----- index.php --------------------------------------



  
  Lector





----- reader.php -------------------------------------
  function ConvertToMimeType($fileLocation) {
    $MimeTypes = array('audio/aac', 'application/x-abiword', 'application/octet-stream', 'video/x-msvideo', 'application/vnd.amazon.ebook', 'application/octet-stream', 'application/x-bzip', 'application/x-bzip2', 'application/x-csh', 'text/css', 'text/csv', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-fontobject', 'application/epub+zip', 'application/ecmascript', 'image/gif', 'text/html', 'image/x-icon', 'text/calendar', 'application/java-archive', 'image/jpeg', 'image/jpg', 'application/javascript', 'application/json', 'audio/midi', 'video/mpeg', 'application/vnd.apple.installer+xml', 'application/vnd.oasis.opendocument.presentation', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.text', 'audio/ogg', 'video/ogg', 'application/ogg', 'font/otf', 'image/png', 'application/pdf', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-rar-compressed', 'application/rtf', 'application/x-sh', 'image/svg+xml', 'application/x-shockwave-flash', 'application/x-tar', 'image/tiff', 'application/typescript', 'font/ttf', 'application/vnd.visio', 'audio/wav', 'audio/webm', 'video/webm', 'image/webp', 'font/woff', 'font/woff2', 'application/xhtml+xml', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/xml', 'application/vnd.mozilla.xul+xml', 'application/zip', 'video/3gpp', 'audio/3gpp', 'video/3gpp2', 'audio/3gpp2', 'application/x-7z-compressed');
    
    $fileInfo = new finfo(FILEINFO_MIME);
    $fileMimeType = $fileInfo->file($fileLocation);
    
    $fileMime = 'application/octet-stream';
    if(in_array($fileMimeType, $MimeTypes))
    {
      $fileMime = $fileMimeType;
    }
    return $fileMime;
  }
  
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
  
  $out = fopen('php://output', 'w'); //output handler
  
  $folderSeparator = '\\';
  $path = __DIR__.$folderSeparator;
  $fileName = NULL;
  
  $aleatorio = rand(1,2);
  
  
  if($aleatorio == 1)
    $fileName = 'somefile.png';
  else
    $fileName = 'denegate-access-image.png';
  
  $urlFile = $path.$fileName;
  $fileSize = filesize($urlFile);
  
  $handleFile = fopen($urlFile, 'r');
  
  $contents = fpassthru($handleFile);
  //other form to do sameting
  //$contents = fread($handleFile, $fileSize);
    
  header('Content-disposition: filename="' . $fileName . '"');
  header('Pragma: no-cache');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header("Content-type: " . ConvertToMimeType($urlFile));
  header("Content-Transfer-Encoding: binary");
  header('Content-Length: '.$fileSize);
  
  echo $contents;
  //other forms to do sameting
  //print file_get_contents($fn);
  //fputs($out, $contents); //writing output operation
  
  
  fclose($out); //closing handler
This functions check recursive permissions and recursive existence parent folders, before creating a folder. To avoid the generation of errors/warnings. 
/**
 * This functions check recursive permissions and recursive existence parent folders,
 * before creating a folder. To avoid the generation of errors/warnings. 
 *
 * @return bool
 *   true folder has been created or exist and writable. 
 *   False folder not exist and cannot be created. 
 */
function createWritableFolder($folder)
{
  if (file_exists($folder)) {
    // Folder exist.
    return is_writable($folder);
  }
  // Folder not exit, check parent folder.
  $folderParent = dirname($folder);
  if($folderParent != '.' && $folderParent != '/' ) {
    if(!createWritableFolder(dirname($folder))) {
      // Failed to create folder parent.
      return false;
    }
    // Folder parent created.
  }
  if ( is_writable($folderParent) ) {
    // Folder parent is writable.
    if ( mkdir($folder, 0777, true) ) {
      // Folder created.
      return true;
    }
    // Failed to create folder.
  }
  // Folder parent is not writable.
  return false;
}
/**
 * This functions check recursive permissions and recursive existence parent folders,
 * before creating a file/folder. To avoid the generation of errors/warnings. 
 *
 * @return bool
 *   true has been created or file exist and writable. 
 *   False file not exist and cannot be created. 
 */
function createWritableFile($file)
{
  // Check if conf file exist.
  if (file_exists($file)) {
    // check if conf file is writable.
    return is_writable($file);
  }
  // Check if conf folder exist and try to create conf file.
  if(createWritableFolder(dirname($file)) && ($handle = fopen($file, 'a'))) {
    fclose($handle);
    return true; // File conf created.
  }
  // Inaccessible conf file.
  return false;
}
Seems not documented here but keep in mind, when $filename contains null byte (\0) then a TypeError will be thrown with message such;
TypeError: fopen() expects parameter 1 to be a valid path, string given in ...
download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files: 
"Do not use the following reserved device names for the name of a file:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, 
LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names 
followed immediately by an extension; for example, NUL.txt is not recommended. 
For more information, see Namespaces"
it is a windows limitation.
see:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
when using ssl / https on windows i would get the error:
"Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"
This was because I did not have the extension "php_openssl.dll" enabled.
So if you have the same problem, goto your php.ini file and enable it :)
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser. After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:
https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700
Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:
/usr/sbin/setsebool httpd_can_network_connect=1
To make the change permanent, run it with the -P option:
/usr/sbin/setsebool -P httpd_can_network_connect=1
Hope this helps others out -- it sure took me a long time to track down the problem.
While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue. 

Example usage:

Hope it helps.
PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.
For example:

Will open the directory if $somefile = ''
If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.
This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.
I was working on a consol script for win32 and noticed a few things about it. On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on. Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway. The number of characters returned is ok, but it will not halt reading and return to the script. I don't know of a work around for this right now, but i'll keep working on it.
This is some code to work around the close and re-open of stdin.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)