Fopen get error message

I'm using fopen to read from a file $fh = fopen($path, 'r') or die('Could not open file'); Now I contantly get error Could not open file. I checked the file path and even changed the permissions ...

I’m using fopen to read from a file

$fh = fopen($path, 'r') or die('Could not open file');

Now I contantly get error Could not open file. I checked the file path and even changed the permissions of the file to 777. Is there a way I can get a detailed error report as why the file can’t be opened similar to mysql_error()?

Adexe Rivera's user avatar

asked Mar 18, 2010 at 13:48

Elitmiar's user avatar

Turn on error reporting, or, in a production environment (from PHP 5.2.0 onwards) you should also be able to use error_get_last().

Seth Carnegie's user avatar

Seth Carnegie

73.3k22 gold badges178 silver badges249 bronze badges

answered Mar 18, 2010 at 13:54

Pekka's user avatar

PekkaPekka

438k140 gold badges968 silver badges1083 bronze badges

0

For php versions prior to 5.2 (lacking error_get_last()) you can use track_errors.

ini_set('track_errors', 1);
$fh = fopen('lalala', 'r');
if ( !$fh ) {
  echo 'fopen failed. reason: ', $php_errormsg;
}

see also: http://de.php.net/reserved.variables.phperrormsg

answered Mar 18, 2010 at 13:54

VolkerK's user avatar

VolkerKVolkerK

94.9k20 gold badges162 silver badges226 bronze badges

0

Yes.
PHP has detailed error message for you.
You just have to turn it on.

To dislay it on the screen add these 2 lines at the top of the script:

ini_set('display_errors',1);
error_reporting(E_ALL);

Or if you want it to be logged instead,

ini_set('log_errors',1);
ini_set('display_errors',0);
error_reporting(E_ALL);

Also note that using die() is very bad practice.

answered Mar 18, 2010 at 13:51

Your Common Sense's user avatar

Your Common SenseYour Common Sense

157k39 gold badges211 silver badges335 bronze badges

$fh = fopen($path, 'r') or  die (error_get_last());

answered May 20, 2016 at 17:44

0

(PHP 4, PHP 5, PHP 7, PHP 8)

fopenOpens file or URL

Description

fopen(
    string $filename,
    string $mode,
    bool $use_include_path = false,
    ?resource $context = null
): resource|false

Parameters

filename

If filename is of the form «scheme://…», it
is assumed to be a URL and PHP will search for a protocol handler
(also known as a wrapper) for that scheme. If no wrappers for that
protocol are registered, PHP will emit a notice to help you track
potential problems in your script and then continue as though
filename specifies a regular file.

If PHP has decided that filename specifies
a local file, then it will try to open a stream on that file.
The file must be accessible to PHP, so you need to ensure that
the file access permissions allow this access.
If you have enabled
open_basedir further
restrictions may apply.

If PHP has decided that filename specifies
a registered protocol, and that protocol is registered as a
network URL, PHP will check to make sure that
allow_url_fopen is
enabled. If it is switched off, PHP will emit a warning and
the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as
wrappers) support context
and/or php.ini options. Refer to the specific page for the
protocol in use for a list of options which can be set. (e.g.
php.ini value user_agent used by the
http wrapper).

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


<?php
$handle
= fopen("c:\folder\resource.txt", "r");
?>

mode

The mode parameter specifies the type of access
you require to the stream. It may be any of the following:


A list of possible modes for fopen()
using mode

mode Description
'r' Open for reading only; place the file pointer at the
beginning of the file.
'r+' Open for reading and writing; place the file pointer at
the beginning of the file.
'w' Open for writing only; place the file pointer at the
beginning of the file and truncate the file to zero length.
If the file does not exist, attempt to create it.
'w+' Open for reading and writing; otherwise it has the
same behavior as 'w'.
'a' Open for writing only; place the file pointer at the end of
the file. If the file does not exist, attempt to create it.
In this mode, fseek() has no effect, writes are always appended.
'a+' Open for reading and writing; place the file pointer at
the end of the file. If the file does not exist, attempt to
create it. In this mode, fseek() only affects
the reading position, writes are always appended.
'x' Create and open for writing only; place the file pointer at the
beginning of the file. If the file already exists, the
fopen() call will fail by returning false and
generating an error of level E_WARNING. If
the file does not exist, attempt to create it. This is equivalent
to specifying O_EXCL|O_CREAT flags for the
underlying open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the
same behavior as '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 (see flock())
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'.
'e' Set close-on-exec flag on the opened file descriptor. Only
available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending
conventions. When you write a text file and want to insert a line
break, you need to use the correct line-ending character(s) for your
operating system. Unix based systems use n as the
line ending character, Windows based systems use rn
as the line ending characters and Macintosh based systems (Mac OS Classic) used
r as the line ending character.

If you use the wrong line ending characters when writing your files, you
might find that other applications that open those files will «look
funny».

Windows offers a text-mode translation flag ('t')
which will transparently translate n to
rn when working with the file. In contrast, you
can also use 'b' to force binary mode, which will not
translate your data. To use these flags, specify either
'b' or 't' as the last character
of the mode parameter.

The default translation mode is 'b'.
You can use the 't'
mode if you are working with plain-text files and you use
n to delimit your line endings in your script, but
expect your files to be readable with applications such as old versions of notepad. You
should use the 'b' in all other cases.

If you specify the ‘t’ flag when working with binary files, you
may experience strange problems with your data, including broken image
files and strange problems with rn characters.

Note:

For portability, it is also strongly recommended that
you re-write code that uses or relies upon the 't'
mode so that it uses the correct line endings and
'b' mode instead.

Note:

The mode is ignored for php://output,
php://input, php://stdin,
php://stdout, php://stderr and
php://fd stream wrappers.

use_include_path

The optional third use_include_path parameter
can be set to ‘1’ or true if you want to search for the file in the
include_path, too.

context

A context stream
resource.

Return Values

Returns a file pointer resource on success,
or false on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Changelog

Version Description
7.0.16, 7.1.2 The 'e' option was added.

Examples

Example #1 fopen() examples


<?php
$handle
= fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Notes

Warning

When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as «SSL: Fatal
Protocol Error» when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.

Note:

If you are experiencing problems with reading and writing to files and
you’re using the server module version of PHP, remember to make sure that
the files and directories you’re using are accessible to the server
process.

Note:

This function may also succeed when filename is a
directory. If you are unsure whether filename is a
file or a directory, you may need to use the is_dir()
function before calling fopen().

See Also

  • Supported Protocols and Wrappers
  • fclose() — Closes an open file pointer
  • fgets() — Gets line from file pointer
  • fread() — Binary-safe file read
  • fwrite() — Binary-safe file write
  • fsockopen() — Open Internet or Unix domain socket connection
  • file() — Reads entire file into an array
  • file_exists() — Checks whether a file or directory exists
  • is_readable() — Tells whether a file exists and is readable
  • stream_set_timeout() — Set timeout period on a stream
  • popen() — Opens process file pointer
  • stream_context_create() — Creates a stream context
  • umask() — Changes the current umask
  • SplFileObject

chapman at worldtakeoverindustries dot com

10 years ago


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.

Anon.

2 years ago


/***** GENTLE REMINDER *****/
Really important. Do NOT use the "w" flag unless you want to delete everything in the file.

php at delhelsa dot com

14 years ago


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.


petepostma-deletethis at gmail dot com

5 years ago


The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:

Mode,Creates,Reads,Writes,Pointer Starts,Truncates File,Notes,Purpose
r,,y,,beginning,,fails if file doesn't exist,basic read existing file
r+,,y,y,beginning,,fails if file doesn't exist,basic r/w existing file
w,y,,y,beginning+end,y,,"create, erase, write file"
w+,y,y,y,beginning+end,y,,"create, erase, write file with read option"
a,y,,y,end,,,"write from end of file, create if needed"
a+,y,y,y,end,,,"write from end of file, create if needed, with read options"
x,y,,y,beginning,,fails if file exists,"like w, but prevents over-writing an existing file"
x+,y,y,y,beginning,,fails if file exists,"like w+, but prevents over writing an existing file"
c,y,,y,beginning,,,open/create a file for writing without deleting current content
c+,y,y,y,beginning,,,"open/create a file that is read, and then written back down"


durwood at speakeasy dot NOSPAM dot net

17 years ago


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.


ideacode

17 years ago


Note that whether you may open directories is operating system dependent. The following lines:

<?php
// Windows ($fh === false)
$fh = fopen('c:\Temp', 'r');// UNIX (is_resource($fh) === true)
$fh = fopen('/tmp', 'r');
?>

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.


php-manual at merlindynamics dot com

2 years ago


There is an undocumented mode for making fopen non-blocking (not working on windows). By adding 'n' to the mode parameter, fopen will not block, however if the pipe does not exist an error will be raised.

$fp = fopen("/tmp/debug", "a"); //blocks if pipe does not exist

$fp = fopen("/tmp/debug", "an"); //raises error on pipe not exist


php at richardneill dot org

11 years ago


fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode.  (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!

splogamurugan at gmail dot com

11 years ago


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. 

<?php

function utf8_fopen_read($fileName) {

   
$fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));

   
$handle=fopen("php://memory", "rw");

   
fwrite($handle, $fc);

   
fseek($handle, 0);

    return
$handle;

}

?>



Example usage:

<?php

$fh
= utf8_fopen_read("./tpKpiBundle.csv");

while ((
$data = fgetcsv($fh, 1000, ",")) !== false) {

    foreach (
$data as $value) {

        echo
$value . "<br />n";

    }

}

?>



Hope it helps.


etters dot ayoub at gmail dot com

5 years ago


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;
}


info at b1g dot de

17 years ago


Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

<?php

#usage:

$r = new HTTPRequest('http://www.example.com');

echo
$r->DownloadToString();

class

HTTPRequest

{

    var
$_fp;        // HTTP socket

   
var $_url;        // full URL

   
var $_host;        // HTTP host

   
var $_protocol;    // protocol (HTTP/HTTPS)

   
var $_uri;        // request URI

   
var $_port;        // port

   
    // scan url

function _scan_url()

    {

       
$req = $this->_url;
$pos = strpos($req, '://');

       
$this->_protocol = strtolower(substr($req, 0, $pos));
$req = substr($req, $pos+3);

       
$pos = strpos($req, '/');

        if(
$pos === false)

           
$pos = strlen($req);

       
$host = substr($req, 0, $pos);

       
        if(

strpos($host, ':') !== false)

        {

            list(
$this->_host, $this->_port) = explode(':', $host);

        }

        else

        {

           
$this->_host = $host;

           
$this->_port = ($this->_protocol == 'https') ? 443 : 80;

        }
$this->_uri = substr($req, $pos);

        if(
$this->_uri == '')

           
$this->_uri = '/';

    }
// constructor

   
function HTTPRequest($url)

    {

       
$this->_url = $url;

       
$this->_scan_url();

    }
// download URL to string

   
function DownloadToString()

    {

       
$crlf = "rn";
// generate request

       
$req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf

           
.    'Host: ' . $this->_host . $crlf

           
.    $crlf;
// fetch

       
$this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);

       
fwrite($this->_fp, $req);

        while(
is_resource($this->_fp) && $this->_fp && !feof($this->_fp))

           
$response .= fread($this->_fp, 1024);

       
fclose($this->_fp);
// split header and body

       
$pos = strpos($response, $crlf . $crlf);

        if(
$pos === false)

            return(
$response);

       
$header = substr($response, 0, $pos);

       
$body = substr($response, $pos + 2 * strlen($crlf));
// parse headers

       
$headers = array();

       
$lines = explode($crlf, $header);

        foreach(
$lines as $line)

            if((
$pos = strpos($line, ':')) !== false)

               
$headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
// redirection?

       
if(isset($headers['location']))

        {

           
$http = new HTTPRequest($headers['location']);

            return(
$http->DownloadToString($http));

        }

        else

        {

            return(
$body);

        }

    }

}

?>


dan at cleandns dot com

19 years ago


<?php
#going to update last users counter script since
#aborting a write because a file is locked is not correct.
$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
if (file_exists($counter_file)) {
  
$fh = fopen($counter_file, 'r+');
    while(
1) {
      if (
flock($fh, LOCK_EX)) {
        
#$buffer = chop(fgets($fh, 2));
        
$buffer = chop(fread($fh, filesize($counter_file)));
        
$buffer++;
        
rewind($fh);
        
fwrite($fh, $buffer);
        
fflush($fh);
        
ftruncate($fh, ftell($fh));    
        
flock($fh, LOCK_UN);
         break;
      }
   }
}
else {
  
$fh = fopen($counter_file, 'w+');
  
fwrite($fh, "1");
  
$buffer="1";
}
fclose($fh);

print

"Count is $buffer";?>

apathetic012 at gmail dot com

10 years ago


a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.

ken dot gregg at rwre dot com

19 years ago


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:

<?php

$fd
= fopen('/home/mydir/' . $somefile, 'r');

?>



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.


Derrick

27 days ago


Opening a file in "r+" mode, and then trying to set the file pointer position with ftruncate before reading the file will result in file data loss, as though you opened the file in "w" mode.

EX:

$File = fopen($FilePath,"r+");  // OPEN FILE IN READ-WRITE

ftruncate($File, 0);  // SET POINTER POSITION (Will Erase Data)

while(! feof($File)) {  // CONTINUE UNTIL END OF FILE IS REACHED

    $Line = fgets($File);  // GET A LINE FROM THE FILE INTO STRING
    $Line = trim($Line);  // TRIM STRING OF NEW LINE
}

ftruncate($File,0); // (Will Not Erase Data)

fclose($File);


flobee

17 years ago


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:
<?php
function download($file_source, $file_target) {
       
$rh = fopen($file_source, 'rb');
       
$wh = fopen($file_target, 'wb');
        if (
$rh===false || $wh===false) {
// error reading or opening file
          
return true;
        }
        while (!
feof($rh)) {
            if (
fwrite($wh, fread($rh, 1024)) === FALSE) {
                  
// 'Download error: Cannot write to file ('.$file_target.')';
                  
return true;
               }
        }
       
fclose($rh);
       
fclose($wh);
       
// No error
       
return false;
    }
?>

ceo at l-i-e dot com

16 years ago


If you need fopen() on a URL to timeout, you can do like:
<?php
  $timeout
= 3;
 
$old = ini_set('default_socket_timeout', $timeout);
 
$file = fopen('http://example.com', 'r');
 
ini_set('default_socket_timeout', $old);
 
stream_set_timeout($file, $timeout);
 
stream_set_blocking($file, 0);
 
//the rest is standard
?>

kasper at webmasteren dot eu

10 years ago


"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

keithm at aoeex dot NOSPAM dot com

21 years ago


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.

<?php

function read($length='255'){

    if (!isset(
$GLOBALS['StdinPointer'])){

       
$GLOBALS['StdinPointer']=fopen("php://stdin","r");

    }

   
$line=fgets($GLOBALS['StdinPointer'],$length);

    return
trim($line);

}

echo
"Enter your name: ";

$name=read();

echo
"Enter your age: ";

$age=read();

echo
"Hi $name, Isn't it Great to be $age years old?";

@
fclose($StdinPointer);

?>


k-gun at git dot io

3 years ago


Seems not documented here but keep in mind, when $filename contains null byte () then a TypeError will be thrown with message such;

TypeError: fopen() expects parameter 1 to be a valid path, string given in ...


wvss at gmail dot com

8 months ago


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<?php
// generiereHostliste.phpfunction generiereHostliste($file) {// aus Rechnerliste.csv lesen
  
$fp = fopen($file, "r");
   while(
$row = fgetcsv($fp, 0, ";")) {      
       
$liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

           } 

fclose($fp);// in Hostliste.csv schreiben
  
$fp = fopen("Hostliste.csv", "w");
   foreach(
$liste as $row) {
       echo
"<pre>";
      
print_r($row);
       echo
"</pre>";
       
fputcsv($fp, $row, ";");
   }
  
fclose($fp);
}
// Test
$file = "Rechnerliste.csv";
generiereHostliste($file);?>
</body>
</html>

wvss at gmail dot com

8 months ago


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<?php
// generiereHostliste.phpfunction generiereHostliste($file) {// aus Rechnerliste.csv lesen
  
$fp = fopen($file, "r");
   while(
$row = fgetcsv($fp, 0, ";")) {      
       
$liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

           } 

fclose($fp);// in Hostliste.csv schreiben
  
$fp = fopen("Hostliste.csv", "w");
   foreach(
$liste as $row) {
       echo
"<pre>";
      
print_r($row);
       echo
"</pre>";
       
fputcsv($fp, $row, ";");
   }
  
fclose($fp);
}
// Test
$file = "Rechnerliste.csv";
generiereHostliste($file);?>
</body>
</html>

sean downey

15 years ago


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 :)


It is quite common that errors may occur while reading data from a file in C++ or writing data to a file. For example, an error may arise due to the following:

  • When trying to read a file beyond indicator.
  • When trying to read a file that does not exist.
  • When trying to use a file that has not been opened.
  • When trying to use a file in an inappropriate mode i.e., writing data to a file that has been opened for reading.
  • When writing to a file that is write-protected i.e., trying to write to a read-only file.

Failure to check for errors then the program may behave abnormally therefore an unchecked error may result in premature termination for the program or incorrect output.

Below are some Error handling functions during file operations in C/C++:

ferror():

In C/C++, the library function ferror() is used to check for the error in the stream. Its prototype is written as:

 int ferror (FILE *stream);

The ferror() function checks for any error in the stream. It returns a value zero if no error has occurred and a non-zero value if there is an error. The error indication will last until the file is closed unless it is cleared by the clearerr() function. 

Below is the program to implement the use of ferror():

C

#include <stdio.h>

#include <stdlib.h>

int main()

{

    FILE* fp;

    char feedback[100];

    int i;

    fp = fopen("GeeksForGeeks.TXT", "w");

    if (fp == NULL) {

        printf("n The file could "

               "not be opened");

        exit(1);

    }

    printf("n Provide feedback on "

           "this article: ");

    fgets(feedback, 100, stdin);

    for (i = 0; i < feedback[i]; i++)

        fputc(feedback[i], fp);

    if (ferror(fp)) {

        printf("n Error writing in file");

        exit(1);

    }

    fclose(fp);

}

C++

#include <bits/stdc++.h>

int main()

{

    FILE* fp;

    char feedback[100];

    int i;

    fp = fopen("GeeksForGeeks.TXT", "w");

    if (fp == NULL) {

        printf("n The file could "

               "not be opened");

        exit(1);

    }

    printf("n Provide feedback on "

           "this article: ");

    fgets(feedback, 100, stdin);

    for (i = 0; i < feedback[i]; i++)

        fputc(feedback[i], fp);

    if (ferror(fp)) {

        printf("n Error writing in file");

        exit(1);

    }

    fclose(fp);

}

Output:

Explanation: After executing this code “Provide feedback on this article:“ will be displayed on the screen and after giving some feedback “Process exited after some seconds with return value 0″ will be displayed on the screen.

clearerr():

The function clearerr() is used to clear the end-of-file and error indicators for the stream. Its prototype can be given as:

void clearerr(FILE *stream);

The clearerr() clears the error for the stream pointed by the stream. The function is used because error indicators are not automatically cleared. Once the error indicator for a specific stream is set, operations on the stream continue to return an error value until clearerr(), fseek(), fsetpos(), or rewind() is called.

Below is the program to implement the use of clearerr():

C

#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

int main()

{

    FILE* fp;

    char feedback[100];

    char c;

    fp = fopen("file.txt", "w");

    c = fgetc(fp);

    if (ferror(fp)) {

        printf("Error in reading from"

               " file : file.txtn");

    }

    clearerr(fp);

    if (ferror(fp)) {

        printf("Error in reading from "

               "file : file.txtn");

    }

    fclose(fp);

}

C++

#include <bits/stdc++.h>

int main()

{

    FILE* fp;

    char feedback[100];

    char c;

    fp = fopen("file.txt", "w");

    c = fgetc(fp);

    if (ferror(fp)) {

        printf("Error in reading from"

               " file : file.txtn");

    }

    clearerr(fp);

    if (ferror(fp)) {

        printf("Error in reading from "

               "file : file.txtn");

    }

    fclose(fp);

}

Output:

The function perror() stands for print error. In case of an error, the programmer can determine the type of error that has occurred using the perror() function. When perror() is called, then it displays a message describing the most recent error that occurred during a library function call or system call. Its prototype can be given as:

void perror (char*msg);

  • The perror() takes one argument which points to an optional user-defined message the message is printed first followed by a colon and the implementation-defined message that describes the most recent error.
  • If a call to perror() is made when no error has actually occurred then ‘No error’ will be displayed.
  • The most important thing to remember is that a call to perror() and nothing is done to deal with the error condition, then it is entirely up to the program to take action. For example, the program may prompt the user to do something such as terminate the program.
  • Usually, the program’s activities will be determined by checking the value of errno and the nature of the error.
  • In order to use the external constant errno, you must include the header file ERRNO.H

Below is the program given below illustrates the use of perror(). Here, assume that the file “file.txt” does not exist.

C

#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

int main()

{

    FILE* fp;

    rename("file.txt", "newfile.txt");

    fp = fopen("file.txt", "r");

    if (fp == NULL) {

        perror("Error: ");

        return (-1);

    }

    fclose(fp);

    return (0);

}

C++

#include <bits/stdc++.h>

#include <errno.h>

int main()

{

    FILE* fp;

    rename("file.txt", "newfile.txt");

    fp = fopen("file.txt", "r");

    if (fp == NULL) {

        perror("Error: ");

        return (-1);

    }

    fclose(fp);

    return (0);

}

Output:

Содержание

  1. fopen
  2. Description
  3. Parameters
  4. Return Values
  5. Errors/Exceptions
  6. Changelog
  7. Examples
  8. Notes
  9. See Also
  10. fopen_s , _wfopen_s
  11. Синтаксис
  12. Параметры
  13. Возвращаемое значение
  14. Условия ошибок
  15. Комментарии
  16. Поддержка Юникода
  17. Кодировки, используемые на ccs основе флага и BOM
  18. Требования

fopen

(PHP 4, PHP 5, PHP 7, PHP 8)

fopen — Opens file or URL

Description

fopen() binds a named resource, specified by filename , to a stream.

Parameters

If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

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

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode

mode Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; otherwise it has the same behavior as ‘w’ .
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘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 (see flock() ) 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’ .
‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use n as the line ending character, Windows based systems use rn as the line ending characters and Macintosh based systems (Mac OS Classic) used r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».

Windows offers a text-mode translation flag ( ‘t’ ) which will transparently translate n to rn when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

The default translation mode is ‘b’ . You can use the ‘t’ mode if you are working with plain-text files and you use n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the ‘b’ in all other cases.

If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with rn characters.

For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.

Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.

The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.

Return Values

Returns a file pointer resource on success, or false on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Changelog

Version Description
7.0.16, 7.1.2 The ‘e’ option was added.

Examples

Example #1 fopen() examples

Notes

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

If you are experiencing problems with reading and writing to files and you’re using the server module version of PHP, remember to make sure that the files and directories you’re using are accessible to the server process.

This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen() .

See Also

  • Supported Protocols and Wrappers
  • fclose() — Closes an open file pointer
  • fgets() — Gets line from file pointer
  • fread() — Binary-safe file read
  • fwrite() — Binary-safe file write
  • fsockopen() — Open Internet or Unix domain socket connection
  • file() — Reads entire file into an array
  • file_exists() — Checks whether a file or directory exists
  • is_readable() — Tells whether a file exists and is readable
  • stream_set_timeout() — Set timeout period on a stream
  • popen() — Opens process file pointer
  • stream_context_create() — Creates a stream context
  • umask() — Changes the current umask
  • SplFileObject

Источник

fopen_s , _wfopen_s

Синтаксис

Параметры

pFile
Указатель на файловый указатель, который получит указатель на открытый файл.

mode
Тип разрешенного доступа.

Возвращаемое значение

Возвращает нуль в случае успеха или код ошибки в случае неудачи. Дополнительные сведения об этих кодах ошибок см. в разделе errno , _doserrno и _sys_errlist _sys_nerr .

Условия ошибок

pFile filename mode Возвращаемое значение Содержимое pFile
NULL any any EINVAL без изменений
any NULL any EINVAL без изменений
any any NULL EINVAL без изменений

Комментарии

_wfopen_s Не fopen_s удается открыть файл для общего доступа. Если необходимо предоставить общий доступ к файлу, используйте или _wfsopen с соответствующей константой режима общего доступа, например, используйте _fsopen _SH_DENYNO для общего доступа на чтение и запись.

Функция fopen_s открывает файл, заданный параметром filename . _wfopen_s — это двухбайтовая версия fopen_s ; аргументы для _wfopen_s представляют собой двухбайтовые строки. Поведение _wfopen_s и fopen_s идентично в противном случае.

Функция fopen_s принимает пути, допустимые в файловой системе во время выполнения; UNC-пути и пути, в которых фигурируют сопоставленные сетевых диски, принимаются функцией fopen_s , если система, которая выполняет код, имеет доступ к общему или сетевому диску в момент выполнения. При построении путей для fopen_s убедитесь, что драйверы, пути или сетевые общие папки будут доступны в среде выполнения. В пути в качестве разделителей каталогов можно использовать прямую (/) или обратную () косую черту.

Эти функции проверяют свои параметры. Если pFile , filename или mode является пустым указателем, эти функции создают недопустимое исключение параметров, как описано в проверке параметров.

Всегда проверяйте возвращаемое значение, чтобы узнать, успешно ли выполнена функция, прежде чем выполнять дальнейшие операции с файлом. При возникновении ошибки возвращается код ошибки, а глобальная переменная errno задается. Дополнительные сведения см. в разделе errno , _doserrno и _sys_errlist _sys_nerr .

По умолчанию глобальное состояние этой функции ограничивается приложением. Сведения об изменении см. в разделе «Глобальное состояние» в CRT.

Поддержка Юникода

fopen_s поддерживает файловые потоки Юникода. Чтобы открыть новый или существующий файл Юникода, передайте флаг, указывающий нужную ccs кодировку fopen_s , например:

Допустимые значения флага ccs : UNICODE , UTF-8 и UTF-16LE . Если для параметра anSI не указано ccs значение, fopen_s используется кодировка ANSI.

Если файл уже существует и открыт для чтения или добавления, то метка порядка байтов (BOM), если она присутствует в файле, определяет кодировку. Кодировка, заданная меткой BOM, имеет приоритет над кодировкой, заданной флагом ccs . Заданная флагом ccs кодировка используется, только если метка BOM отсутствует или речь идет о новом файле.

Обнаружение метки BOM применяется только к файлам, которые будут открываться в режиме Юникода (т. е. путем передачи флага ccs ).

В следующей таблице перечислены режимы для различных ccs значений флагов, которые предоставляются fopen_s и для boms в файле.

Кодировки, используемые на ccs основе флага и BOM

Флаг ccs Нет метки BOM (или новый файл) BOM: UTF-8 BOM: UTF-16
UNICODE UTF-8 UTF-8 UTF-16LE
UTF-8 UTF-8 UTF-8 UTF-16LE
UTF-16LE UTF-16LE UTF-8 UTF-16LE

В файлы, открываемые для записи в режиме Юникода, метка BOM записывается автоматически.

В mode противном «a, ccs=UNICODE» «a, ccs=UTF-8» «a, ccs=UTF-16LE» fopen_s случае сначала пытается открыть файл с доступом на чтение и запись. Если эта операция завершается успешно, функция считывает метку BOM, чтобы определить кодировку для файла; если операция завершается сбоем, функция использует для файла кодировку по умолчанию. В любом случае fopen_s снова открывает файл с доступом только для записи. (Это поведение применяется только к режиму a , а не a+ к .)

Символьная строка mode указывает тип доступа, который запрошен для файла, следующим образом.

mode Access
«r» Открывает для чтения. Если файл не существует или не удается найти, вызов завершается сбоем fopen_s .
«w» Открывает пустой файл для записи. Если указанный файл существует, его содержимое удаляется.
«a» Открывается для записи в конце файла (добавление) без удаления маркера в конце файла (EOF) перед записью новых данных в файл. Создает файл, если он не существует.
«r+» Открывает для чтения и записи. Файл должен существовать.
«w+» Открывает пустой файл для чтения и записи. Если файл существует, его содержимое удаляется.
«a+» Открывается для чтения и добавления. Операция добавления включает удаления маркера EOF перед записью новых данных в файл. Маркер EOF не восстанавливается после завершения записи. Создает файл, если он не существует.

Если файл открывается с использованием типа доступа «a» или «a+» , все операции записи выполняются в конце файла. Указатель на файл можно изменить с помощью fseek или rewind , но он всегда перемещается обратно в конец файла до выполнения любой операции записи, чтобы существующие данные не могли быть перезаписаны.

Режим «a» не удаляет маркер EOF перед добавлением в файл. После добавления команда MS-DOS TYPE отображает только данные до исходного маркера EOF, а не какие-либо данные, добавленные в файл. Перед добавлением в файл режим «a+» удаляет маркер конца файла. После добавления команда MS-DOS TYPE отображает все данные в файле. Этот «a+» режим необходим для добавления в потоковый файл, который завершается маркером CTRL +Z EOF.

«r+» Если указан тип доступа , «w+» или «a+» тип доступа, разрешено чтение и запись. (Файл, как утверждается, открыт для «обновления».) Однако при переходе с чтения на запись операция ввода должна сталкиваться с маркером EOF. Если маркер EOF отсутствует, необходимо использовать промежуточный вызов функции позиционирования файлов. Функции позиционирования в файле — это fsetpos , fseek и rewind . При переходе от записи к чтению необходимо воспользоваться промежуточным вызовом либо функции fflush , либо функции позиционирования в файле.

Начиная с C11, можно добавить «x» «w» или «w+» вызвать сбой функции, если файл существует, а не перезаписывать его.

Помимо приведенных выше значений, можно включить mode следующие символы, чтобы указать режим перевода для символов новой строки:

mode Модификатор Режим перевода
t Откройте файл в текстовом (переведенном) режиме.
b Открытие в двоичном (неперекрытом) режиме; Переводы, включающие символы возврата каретки и строки, подавляются.

В текстовом (переведенном) режиме CTRL +Z интерпретируется как символ конца файла во входных данных. В файлах, открытых для чтения и записи, «a+» fopen_s проверяет CTRL +наличие Z в конце файла и удаляет его, если это возможно. Он удаляется, так как использование fseek и ftell перемещение в файл, заканчивающийся CTRL +Z, может привести fseek к неправильному поведении в конце файла.

Кроме того, в текстовом режиме сочетания возврата каретки и канала строки (CRLF) превратятся в символы однострочного канала (LF) во входных данных, а символы LF переводятся в сочетания CRLF для выходных данных. Если функция ввода-вывода потока Юникода работает в текстовом режиме (по умолчанию) исходный или конечный поток рассматривается как последовательность многобайтовых символов. Функции потокового ввода Юникода преобразуют многобайтовые символы в расширенные символы (как будто при вызове mbtowc функции). По той же причине выходные функции потока Юникода преобразуют расширенные символы в многобайтовые (как если бы для этого вызывалась функция wctomb ).

Если t или b не задано, mode режим перевода по умолчанию определяется глобальной переменной _fmode . Если символ t или b указан как префикс аргумента, функция завершается с ошибкой и возвращает NULL .

Дополнительные сведения об использовании текстовых и двоичных режимов в Юникоде и многобайтовом потоке ввода-вывода см. в разделе «Текстовый и двоичный режим ввода-вывода» и потоковые операции ввода-вывода в Юникоде в текстовых и двоичных режимах.

mode Модификатор Поведение
c Включите флажок фиксации для связанного объекта filename , чтобы содержимое файлового буфера записывалось непосредственно на диск при вызове fflush или _flushall .
n Сбросьте флаг фиксации для связанного filename с «no-commit». Этот флаг используется по умолчанию. Он также переопределяет глобальный флаг фиксации при связывании программы с COMMODE.OBJ . Глобальный флаг фиксации по умолчанию имеет значение «no-commit», если вы явно не свяжите программу с COMMODE.OBJ (см. раздел «Параметры ссылки»).
N Указывает, что файл не наследуется дочерними процессами.
S Указывает, что кэширование оптимизировано для последовательного доступа с диска, но не ограничивается им.
R Указывает, что кэширование оптимизировано для случайного доступа с диска, но не ограничивается им.
t Определяет файл как временный. Если это возможно, он не сбрасывается на диск.
D Определяет файл как временный. Он удаляется при закрытии последнего указателя файла.
ccs=UNICODE Задает ЮНИКОД в качестве закодированного набора символов, который будет использоваться для этого файла. Не указывайте никакое значение, если требуется использовать кодировку ANSI.
ccs=UTF-8 Указывает UTF-8 в качестве закодированного набора символов, который будет использоваться для этого файла. Не указывайте никакое значение, если требуется использовать кодировку ANSI.
ccs=UTF-16LE Указывает UTF-16LE в качестве закодированного набора символов, который будет использоваться для этого файла. Не указывайте никакое значение, если требуется использовать кодировку ANSI.

Допустимые символы для строки, используемой mode в fopen_s , и _fdopen соответствуют oflag аргументам, используемым и _open _sopen как показано ниже.

Символы в строке mode Эквивалентное значение oflag для _open / _sopen
a _O_WRONLY | _O_APPEND (обычно _O_WRONLY | _O_CREAT | _O_APPEND )
a+ _O_RDWR | _O_APPEND (обычно _O_RDWR | _O_APPEND | _O_CREAT )
R _O_RDONLY
r+ _O_RDWR
w _O_WRONLY (обычно _O_WRONLY | _O_CREAT | _O_TRUNC )
w+ _O_RDWR (обычно ** _O_RDWR | _O_CREAT | _O_TRUNC )
b _O_BINARY
t _O_TEXT
c Нет
n Нет
S _O_SEQUENTIAL
R _O_RANDOM
t _O_SHORTLIVED
D _O_TEMPORARY
ccs=UNICODE _O_WTEXT
ccs=UTF-8 _O_UTF8
ccs=UTF-16LE _O_UTF16

t n mode И c параметры — это расширения Майкрософт для fopen_s и _fdopen не должны использоваться, где требуется переносимость ANSI.

Если вы используете rb режим, память сопоставленных файлов Win32 также может быть вариантом, если вам не нужно переносить код, вы ожидаете прочитать большую часть файла или не волнуете производительность сети.

Требования

Компонент Обязательный заголовок Заголовок C++
fopen_s
_wfopen_s или

Дополнительные сведения о соответствии стандартов и соглашениях об именовании в библиотеке среды выполнения C см. в разделе «Совместимость».

Источник

std::FILE* fopen( const char* filename, const char* mode );

Opens a file indicated by filename and returns a file stream associated with that file. mode is used to determine the file access mode.

[edit] Parameters

filename file name to associate the file stream to
mode null-terminated character string determining file access mode

[edit] File access flags

File access
mode string
Meaning Explanation Action if file
already exists
Action if file
does not exist
«r» read Open a file for reading read from start return NULL and set error
«w» write Create a file for writing destroy contents create new
«a» append Append to a file write to end create new
«r+» read extended Open a file for read/write read from start return NULL and set error
«w+» write extended Create a file for read/write destroy contents create new
«a+» append extended Open a file for read/write write to end create new
File access mode flag «b» can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of n and x1A.
On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.
File access mode flag «x» can optionally be appended to «w» or «w+» specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C++17)
The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. Windows).

[edit] Return value

If successful, returns a pointer to the object that controls the opened file stream, with both eof and error bits cleared. The stream is fully buffered unless filename refers to an interactive device.

On error, returns a null pointer. POSIX requires that errno is set in this case.

[edit] Notes

The format of filename is implementation-defined, and does not necessarily refer to a file (e.g. it may be the console or another device accessible through filesystem API). On platforms that support them, filename may include absolute or relative filesystem path.

For portable directory and file naming, see C++ filesystem library or boost.filesystem.

[edit] Example

Output:

End of file reached successfully

[edit] See also

fopen

(PHP 4, PHP 5, PHP 7)

fopenОткрывает файл или URL

Описание

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

Список параметров

filename

Если filename передан в форме «scheme://…»,
он считается URL’ом и PHP проведёт поиск обработчика протокола
(также известного как «обертка») для этой схемы. Если ни одна
обёртка не закреплена за протоколом, PHP выдаст замечание,
чтобы помочь вам отследить потенциальную проблему в вашем
скрипте и затем продолжит выполнение, как если бы filename
указывал на обыкновенный файл.

Если PHP установлено, что filename указывает на
локальный файл, тогда выполняется попытка открыть поток к этому файлу.
Файл должен быть доступен PHP, так что вам следует убедиться,
что права доступа на файл это разрешают.
Если вы включили безопасный режим
или open_basedir, то накладываются
дальнейшие ограничения.

Если PHP установлено, что filename указывает на
зарегистрированный протокол и этот протокол зарегистрирован как
сетевой URL, PHP выполняет проверку состояния директивы
allow_url_fopen.
Если она выключена, PHP выдаст предупреждение и вызов fopen закончится
неудачей.

Замечание:

Список поддерживаемых протоколов доступен в разделе Поддерживаемые протоколы и обработчики (wrappers).
Некоторые протоколы (обертки) поддерживают
контекст и/или опции php.ini.
Обратитесь к соответствующей странице с описанием используемого протокола
для получения списка опций, которые могут быть установлены.
(например, значение php.ini user_agent используется
оберткой http).

На платформе Windows, необходимо экранировать все
обратные слеши в пути к файлу или использовать прямые слеши.


<?php
$handle 
fopen("c:\folder\resource.txt""r");
?>

mode

Параметр mode указывает тип доступа, который вы
запрашиваете у потока. Он может быть одним из следующих вариантов:


Список возможных режимов для fopen()
используя mode

mode Описание
‘r’ Открывает файл только для чтения; помещает указатель
в начало файла.
‘r+’ Открывает файл для чтения и записи; помещает указатель
в начало файла.
‘w’ Открывает файл только для записи; помещает указатель
в начало файла и обрезает файл до нулевой длины.
Если файл не существует — пробует его создать.
‘w+’ Открывает файл для чтения и записи; помещает указатель
в начало файла и обрезает файл до нулевой длины.
Если файл не существует — пытается его создать.
‘a’ Открывает файл только для записи; помещает указатель в конец
файла. Если файл не существует — пытается его создать.
‘a+’ Открывает файл для чтения и записи; помещает указатель в конец
файла. Если файл не существует — пытается его создать.
‘x’ Создаёт и открывает только для записи; помещает указатель в
начало файла. Если файл уже существует, вызов
fopen() закончится неудачей, вернёт FALSE и
выдаст ошибку уровня E_WARNING.
Если файл не существует, попытается его создать. Это эквивалентно
указанию флагов O_EXCL|O_CREAT для внутреннего
системного вызова open(2).
‘x+’ Создаёт и открывает для чтения и записи; иначе имеет то же поведение что и‘x’.
‘c’ Открывает файл только для записи. Если файл не существует, то он создается.
Если же файл существует, то он не обрезается (в отличии от
‘w’), и вызов к этой функции не вызывает ошибку (также как
и в случае с ‘x’). Указатель на файл будет установлен
на начало файла. Это может быть полезно при желании заблокировать
файл (смотри flock()) перед изменением, так как использование
‘w’ может обрезать файл еще до того как была получена блокировка
(если вы желаете обрезать файл, можно использовать функцию
ftruncate() после запроса на блокировку).
‘c+’ Открывает файл для чтения и записи; иначе имеет то же поведение, что и ‘c’.

Замечание:

Разные семейства операционных систем имеют разные соглашения
относительно окончания строк. Когда вы пишете текст и хотите вставить
разрыв строки, вы должны использовать правильные символы (или символ) для
вашей операционной системы. Системы семейства Unix используют
n в качестве символа конца строки, системы
семейства Windows используют rn в качестве
символов окончания строки и системы семейства Macintosh используют
r в качестве символа конца строки.

Если вы используете неверный символ конца строки при редактировании
файлов, вы можете обнаружить, что при открытии эти файлы «странно
выглядят».

Windows предлагает флаг режима текстовой трансляции
(‘t’), который автоматически переведёт
n в rn во время работы с файлом.
И наоборот — вы также можете использовать ‘b’, чтобы
принудительно включить бинарный режим, в котором ваши данные
не будут преобразовываться. Чтобы использовать эти режимы, укажите
‘b’ или ‘t’ последней
буквой параметра mode.

Так как установка флага трансляции по умолчанию зависит от SAPI и используемой версии
PHP, рекомендуем явно задавать указанный флаг
из соображений портируемости. Вы должны использовать режим
‘t’, если вы работаете с текстовым файлом и
использовать n для обозначения
конца строки в вашем скрипте, при этом не беспокоясь за читаемость
ваших файлов в других приложениях типа «Блокнота». Во всех остальных случаях
используйте флаг ‘b’.

Если вы явно не укажете флаг ‘b’ во время работы с бинарными файлами,
вы можете столкнуться со странной порчей ваших данных, включая
испорченные файлы изображений и странные проблемы с символами rn.

Замечание:

Из соображений портируемости, настоятельно рекомендуется всегда
использовать флаг ‘b’ при открытии файлов с помощью fopen().

Замечание:

Кроме того, из соображений портируемости, также настойчиво
рекомендуется переписать старый код, который полагается на режим
‘t’, чтобы вместо этого он использовал правильные
концы строк и режим ‘b’.

use_include_path

Необязательный третий параметр use_include_path
может быть установлен в ‘1’ или TRUE, если вы также хотите провести
поиск файла в include_path.

context

Замечание: Поддержка контекста была добавлена
в PHP 5.0.0. Для описания контекстов смотрите раздел
Потоки.

Возвращаемые значения

Возвращает указатель на файл в случае успешной работы, или FALSE в случае ошибки.

Ошибки

Если открыть файл не удалось, будет сгенерирована ошибка уровня
E_WARNING. Вы можете использовать оператор
@ для подавления этой ошибки.

Список изменений

Версия Описание
5.2.6 Добавлены опции ‘c’ и ‘c+’
4.3.2 С версии PHP 4.3.2, по умолчанию устанавливается бинарный режим для всех платформ, различающих
бинарный и текстовый режимы. Если у вас появились проблемы после обновления,
попытайтесь использовать в качестве обхода проблемы флаг ‘t’, пока
вы не сделаете ваш скрипт более портируемым, как это было указано выше.

Примеры

Пример #1 Примеры использования fopen()


<?php
$handle 
fopen("/home/rasmus/file.txt""r");
$handle fopen("/home/rasmus/file.gif""wb");
$handle fopen("http://www.example.com/""r");
$handle fopen("ftp://user:password@example.com/somefile.txt""w");
?>

Примечания

Внимание

При использовании SSL,
Microsoft IIS нарушает протокол, закрывая соединение без отправки
индикатора close_notify. PHP сообщит об этом как «SSL: Fatal Protocol Error»
в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны
установить error_reporting на
уровень, исключающий E_WARNING.
PHP версий 4.3.7 и старше умеет определять, что на стороне сервера находится
проблемный IIS при открытии потока с помощью обертки https:// и не выводит предупреждение.
Если вы используете fsockopen() для создания ssl:// сокета,
вы сами отвечаете за определение и подавление этого предупреждения.

Замечание: Когда опция safe mode включена, PHP проверяет,
имеет ли каталог, с которым вы собираетесь работать, такой же UID (владельца),
как и выполняемый скрипт.

Замечание:

Если вы сталкиваетесь с проблемами во время чтения или записи
файлов, и вы используете PHP в виде серверного модуля, убедитесь
в том, что процесс сервера имеет доступ к используемым вами файлам и директориям.

Замечание:

Эта функция также может выполниться успешно, в случае если
filename является директорией.
Если вы не уверены является ли filename файлом или директорией,
то вам необходимо воспользоваться функцией is_dir(),
до вызова fopen().

Смотрите также

  • Поддерживаемые протоколы и обработчики (wrappers)
  • fclose() — Закрывает открытый дескриптор файла
  • fgets() — Читает строку из файла
  • fread() — Бинарно-безопасное чтение файла
  • fwrite() — Бинарно-безопасная запись в файл
  • fsockopen() — Открывает соединение с интернет сокетом или доменным сокетом Unix
  • file() — Читает содержимое файла и помещает его в массив
  • file_exists() — Проверяет наличие указанного файла или каталога
  • is_readable() — Определяет существование файла и доступен ли он для чтения
  • stream_set_timeout() — Устанавливает значение тайм-аута на потоке
  • popen() — Открывает файловый указатель процесса
  • stream_context_create() — Создаёт контекст потока
  • umask() — Изменяет текущую umask
  • SplFileObject

Вернуться к: Файловая система

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fopen get error code
  • Footer is wrong error 21
  • Football manager 2023 как изменить лимит
  • Foot switch error перевод
  • Foobar2000 как изменить цвет

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии