search for in the  
<fnmatchfpassthru>
Last updated: Thu, 19 May 2005

fopen

(PHP 3, PHP 4, PHP 5)

fopen -- Opens file or URL

Description

resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )

fopen() binds a named resource, specified by filename, to a stream. 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 safe mode, or 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 Appendix L. 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).

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CXXII, Stream Functions.

Note: As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned below.

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

Table 1. A list of possible modes for fopen() using mode

modeDescription
'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; 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.
'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.
'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.
'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. This option is supported in PHP 4.3.2 and later, and only works for local files.
'x+' Create and open for reading and writing; 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. This option is supported in PHP 4.3.2 and later, and only works for local files.

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 \r\n as the line ending characters and Macintosh based systems use \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 \r\n 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 depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should 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 notepad. You should use the 'b' in all other cases.

If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note: For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

Note: Again, 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.

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.

If the open fails, the function returns FALSE and an error of level E_WARNING is generated. You may use @ to suppress this warning.

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");
?>

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.

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:\\data\\info.txt", "r");
?>

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 workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.

See also Appendix L, fclose(), fgets(), fread(), fwrite(), fsockopen(), file(), file_exists(), is_readable(), stream_set_timeout(), and popen().



User Contributed Notes
fopen
francois AT crevola DOT com
11-May-2005 07:54
In reply to "pflaume dot NOSPAM at NOSPAM dot gmx dot de"
about  fopen() and PROXY

With PHP 5.0.0 and after, you can use a proxy by using a stream context. See the note about "Context support was added with PHP 5.0.0".
06-May-2005 04:58
'fopen' only opens a handle to the file.  You may want to use it in this format;

<?php
$hi
= fopen("myfile.txt","r");
$text = fread($hi,filesize("myfile.txt"));
fclose($hi);
?>

So '$text' would = contents of file, or use this alternative function;

<?php
$hi
= file("myfile.txt");
print_r($hi);
?>

'file' reads the contents of your file, and will store it in the '$hi' variable as an array of lines.  'print_r' will simply print this array in an easy-to-read way.
17-Apr-2005 11:41
This only relavant to those opening a remote file for writing using the PECL SSH2 for SFTP paths for the string filename.  Since SFTP has variations, most of which are non-secure, using this module is the only viable solution.  The optional FTP extension class that uses the function 'ftp_ssl_connect' uses openssl, which only encrypts the communication requests and not the data - or something close to that.  At any rate, many systems will not allow connection to their SFTP server using this method.

I think it's worth mentioning that some of the examples provided in various areas failed consistantly using the syntax given, using both possible methods of.
   ssh2.sftp://$sftp/example.com/path/to/file
   ssh2.sftp://user:pass@$sftp/example.com/path/to/file

It's just a small adjustment to correct this, but as most coding goes, a long road to find a stupid little oversight.  Apparently it is necessary to supply the port as well in the path.  Could just be the few systems I was testing against, but that would be three separate networks using three separate platforms (Windows Server, Linux, Unix).  At any rate, the following works like a charm, and was very simple to install the libssh2 library and PECL SSH2 module required to use this system.  Gotta love PHP.
   ssh2.sftp://$sftp/example.com:22/path/to/file
   ssh2.sftp://user:pass@$sftp:22/example.com/path/to/file

Hope this saves anyone some headache and time.
abesharp at yahoo dot co dot uk
05-Apr-2005 07:12
This function has a basic implementation of HTTP Digest Authentication (as per RFC 2617) to get a file from a web server which requires digest authentication (as opposed to basic authentication - the difference being that, with basic, your password is sent to the server as plain text, whereas with digest, it is hashed with a server-supplied nonce to protect against sniffing and replay attacks).

You just supply the host (e.g www.example.com), the name of the file you want (e.g protected_page.html), and the necessary username and password, and the function returns the contents of the protected file (or the error message that the server sends, if you supplied the wrong credentials).

If the server only supports a QOP of auth-int (rather then auth) this function won't work, but can be easily modified with reference to the RFC at http://www.ietf.org/rfc/rfc2617.txt

<?php
function readHTTPDigestAuthenticatedFile($host,$file,$username,$password)
{
   if (!
$fp=fsockopen($host,80, $errno, $errstr, 15))
       return
false;
      
  
//first do the non-authenticated header so that the server
   //sends back a 401 error containing its nonce and opaque
  
$out = "GET /$file HTTP/1.1\r\n";
      
$out .= "Host: $host\r\n";
      
$out .= "Connection: Close\r\n\r\n";

    
fwrite($fp, $out);

  
//read the reply and look for the WWW-Authenticate element
  
while (!feof($fp))
   {
      
$line=fgets($fp, 512);
      
       if (
strpos($line,"WWW-Authenticate:")!==false)
          
$authline=trim(substr($line,18));
   }
  
  
fclose($fp);
      
  
//split up the WWW-Authenticate string to find digest-realm,nonce and opaque values
   //if qop value is presented as a comma-seperated list (e.g auth,auth-int) then it won't be retrieved correctly
   //but that doesn't matter because going to use 'auth' anyway
  
$authlinearr=explode(",",$authline);
  
$autharr=array();
  
   foreach (
$authlinearr as $el)
   {
      
$elarr=explode("=",$el);
      
//the substr here is used to remove the double quotes from the values
      
$autharr[trim($elarr[0])]=substr($elarr[1],1,strlen($elarr[1])-2);
   }
  
   foreach (
$autharr as $k=>$v)
       echo(
"$k ==> $v\r\n");
  
  
//these are all the vals required from the server
  
$nonce=$autharr['nonce'];
  
$opaque=$autharr['opaque'];
  
$drealm=$autharr['Digest realm'];
  
  
//client nonce can be anything since this authentication session is not going to be persistent
   //likewise for the cookie - just call it MyCookie
  
$cnonce="sausages";
  
  
//calculate the hashes of A1 and A2 as described in RFC 2617
  
$a1="$username:$drealm:$password";$a2="GET:/$file";
  
$ha1=md5($a1);$ha2=md5($a2);
  
  
//calculate the response hash as described in RFC 2617
  
$concat = $ha1.':'.$nonce.':00000001:'.$cnonce.':auth:'.$ha2;
  
$response=md5($concat);
  
  
//put together the Authorization Request Header
  
$out = "GET /$file HTTP/1.1\r\n";
      
$out .= "Host: $host\r\n";
  
$out .= "Connection: Close\r\n";
  
$out .= "Cookie: cookie=MyCookie\r\n";
  
$out .= "Authorization: Digest username=\"$username\", realm=\"$drealm\", qop=\"auth\", algorithm=\"MD5\", uri=\"/$file\", nonce=\"$nonce\", nc=00000001, cnonce=\"$cnonce\", opaque=\"$opaque\", response=\"$response\"\r\n\r\n";
  
   if (!
$fp=fsockopen($host,80, $errno, $errstr, 15))
       return
false;
  
  
fwrite($fp, $out);
  
  
//read in a string which is the contents of the required file
  
while (!feof($fp))
   {
      
$str.=fgets($fp, 512);
   }
  
  
fclose($fp);
  
   return
$str;
}

?>
jyo
15-Mar-2005 09:13
jared at dctkc dot com
Saved my life ! it works !

I succeded in launching caracters on serial port 4 (a virtual device : my peripherial is connected to a USB port). With fwrite it did'nt work. With fputs it's fine !!!
nuno at ideianet dot pt
04-Mar-2005 08:03
In IIS you must add the group Authenticated Users with write and modify permissions in the file where you want to write if you are in a Protected directory (Basic or Digest authentication) and want to write to a file in a Unprotected directory (Anonymous Access) in order to get permission to do that. Otherwise you will get the message: PHP Warning: fopen(x.txt): failed to open stream: Permission denied in c:\web\x\x.php on line 3 PHP Warning: fwrite(): supplied argument is not a valid stream resource in c:\web\x\x.php on line 10
nuno at ideianet dot pt
21-Feb-2005 12:37
In IIS you must add the user IUSR_yourservername (Internet Guest Account) with write and modify permissions in the file where you want to write in order to get permission to do that. Otherwise you will get the message: PHP Warning: fopen(x.txt): failed to open stream: Permission denied in c:\web\x\x.php on line 3 PHP Warning: fwrite(): supplied argument is not a valid stream resource in c:\web\x\x.php on line 10
rodphp - no5pam - redzia - no5pam - com
08-Feb-2005 10:51
Example usage of fopen to remove line containing a key string
<?

$key
= "w3ty8l";

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
     if (!
strstr($line,$key)) //look for $key in each line
          
fputs($f,$line); //place $line back in file
}
fclose($f);

?>
conner_bw
29-Jan-2005 03:35
An improved version of zwiskle's cached_fopen_url(). This accounts for the fact that the destination website might not respond or time out thereby stalling the source server.

<?php
/*******************************************
* Function cached_fopen_url():
* Caches data from a HTTP resource/url to a
* local file (HTTP headers are stipped)
* @returns a file resoruce / or FALSE if failure.
**/
function cached_fopen_url($url, $file_mode, $timeout_seconds = 90, $cache_path = "/yourpath/tmp", $fsocket_timeout = 10)
{
   
   $debug
= true;
   
   clearstatcache
();
   $cache_filename=$cache_path . "/" . urlencode($url) .".cached";
   
   if
($debug) {
      print "local_cache creation_time =" .
      @filemtime($cache_filename) .
      " actual time = " . time() .
      " timeout = " .
      timeout_seconds ."<p>";
   }
   
   if
( ( @file_exists($cache_filename ) and ( ( @filemtime($cache_filename) + $timeout_seconds) > ( time() ) ) ) ) {
      // ok, file is already cached and young enouth
      if ($debug) { print "using cached file ($cache_filename) <p>";}
   } else {
      
      if
($debug) { print "cacheing file ($url) to local ($cache_filename)<p>";}
      
      $urlParts
= parse_url($url);
      $host = $urlParts['host'];
      $port = (isset($urlParts['port'])) ? $urlParts['port'] : 80;
      
      if
( !$fp = @fsockopen( $host, $port, $errno, $errstr, $fsocket_timeout )) {
         // Server not responding
         
      
} else {
         
         if
( !fputs( $fp, "GET $url HTTP/1.0\r\nHost:$host\r\n\r\n" )) {
            die( "unable to send get request" );
         }
         
         $data
= null;
         stream_set_timeout($fp, $fsocket_timeout);   
         $status
= socket_get_status($fp);
         while( !feof($fp) && !$status['timed_out'])         
         
{
            $data .= fgets ($fp,8192);
            $status = socket_get_status($fp);
         }
         fclose ($fp);
         
         
// strip headers
         $sData = split("\r\n\r\n", $data, 2);
         $data = $sData[1];
         
         
// save to cache file
         $f2 = fopen($cache_filename,"w+");
         fwrite($f2,$data);
         fclose($f2);
      }
   }
   
   
// ok, point to (fresh) cached file
   if ( @file_exists($cache_filename )) {
      $handle = fopen($cache_filename, $file_mode);
      return $handle;
   }
   
   return false
;
}
?>
Thomas Candrian tc_ at gmx dot ch
11-Nov-2004 10:35
With this it isn't possible to get data from another port than 80 (and 443) - at least for me. Because of that I've made this function who gets data from every port you want using HTTP:

<?php;
function
getcontent($server, $port, $file)
{
  
$cont = "";
  
$ip = gethostbyname($server);
  
$fp = fsockopen($ip, $port);
   if (!
$fp)
   {
       return
"Unknown";
   }
   else
   {
      
$com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: $server:$port\r\nConnection: Keep-Alive\r\n\r\n";
      
fputs($fp, $com);
       while (!
feof($fp))
       {
          
$cont .= fread($fp, 500);
       }
      
fclose($fp);
      
$cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
       return
$cont;
   }
}
echo
getcontent("www.myhost.com", "81", "/"));
?>

Works fine for me. Had to do this especially for a shoutcast server, which only delivered the HTML-file if the user-agent was given.
pflaume dot NOSPAM at NOSPAM dot gmx dot de
07-Nov-2004 05:31
fopen() and PROXY

I wondered why there is no possibility to use fopen() through a proxy in php. The solution posted above did not work for me.

This little function gets http through a given proxy:

<?php
function proxy_url($proxy_url)
{
  
$proxy_name = '127.0.0.1';
  
$proxy_port = 4001;
  
$proxy_cont = '';

  
$proxy_fp = fsockopen($proxy_name, $proxy_port);
   if (!
$proxy_fp)    {return false;}
  
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n\r\n");
   while(!
feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
  
fclose($proxy_fp);
  
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
   return
$proxy_cont;
}
?>
twenty dot five dot to dot five at gmail dot com
27-Oct-2004 12:19
The first post, in regards to the exploding string, it is much more useful and easier to use a |, but simply when all input is inserted, do a search and replace and replace all | with there ASCII value. This will make it impossible to ruin the script.
wilq at darbud dot com dot pl
07-Oct-2004 11:23
Advice to draconumpb script: better use some longer string than using only "|" because it might have some error when someone who typing new post write this sign in text (i dont know what for but..:>)

something like:  " m|s|0n |mp0ss|ble " could bring an badly decoded string

but strings  like "#@#@#" used in files to separate fields are not so long and much better because there is almost no chance that user type it in text field:) (the best way would be generate something randomically like @#$@#%!@* :>>)
justin at redwiredesign dot com
14-Jul-2004 03:03
One thing worth noting is that if you use the fopen command to open an HTTP stream, and the URL you're trying to access is invalid or generates an error response, (i.e. 404 Not found), the fopen call will return false.
zwiskle at vol dot at
05-Jun-2004 04:04
this smal function can cache local a fopen request. very usefull when you use fopen for http connections (maybe only then) of (more or less) static data. using a proxy might be a solution, but they normaly don't support get-url's ( something.php?query=asdf )

I used it original for a webservice-querying webpage, which reads the WSDL file for accurate parameter-checking...

Speeds up this extremly, and because of the cache-expiration still keep it accurate.

Use at own risk: no error-handling, might also be a security hole, no locking, ...

<?
// cache a (http) fopen - with cache-timeout.
function cached_fopen($file, $file_mode, $timeout_seconds = 600, $cache_path = "/tmp"){

 
$debug=false;
 
 
clearstatcache();
 
$cache_filename=$cache_path . "/" . urlencode($file) .".cached";
 
  if (
$debug) { print "local_cache creation_time =" . @filemtime($cache_filename) . " actual time = " . time() . " timeout = " . $timeout_seconds ."<p>";}
 
  if ( ( @
file_exists($cache_filename ) and ( ( @filemtime($cache_filename) + $timeout_seconds) > ( time() ) ) ) ){
  
// ok, file is already cached and young enouth
    
if ($debug) { print "using cached file ($cache_filename) <p>";}
   } 
  else 
  {
   if (
$debug) { print "cacheing file ($file) to local ($cache_filename)<p>";}

  
// cache file from net to local
  
$f = fopen($file,"r");
  
$f2 = fopen($cache_filename,"w+");
   while (
$r=fread($f,8192) ) {
    
fwrite($f2,$r);
   }
  
fclose($f2);
  
fclose($f);
  }
 
 
// ok, point to (fresh) cached file
 
$handle = fopen($cache_filename, $file_mode);
  return
$handle;

}
?>

usage:

<?
$handle
= cached_fopen("http://example.com/show?xy","r",600)
?>
Jem Tallon
13-Apr-2004 06:11
If you're using fopen to open a URL that requires authorization, you might need to force a HTTP/1.0 request for it since fopen won't support HTTP/1.1 requests. You can do that by setting your user_agent to one that is known only to support HTTP/1.0 (most webservers will be configured to force HTTP/1.0 for some browsers). Here's what worked for me:

<?php
$returned
=URLopen("http://$username:$password@example.com");

function
URLopen($url)
{
      
// Fake the browser type
      
ini_set('user_agent','MSIE 4\.0b2;');

      
$dh = fopen("$url",'r');
      
$result = fread($dh,8192);                                                                                                                           
       return
$result;
}
?>
php at gotdoof dot com
03-Apr-2004 11:19
Note that opening a fifo with fopen() will block the php process until data is sent to it. That means any function you have registered as a shutdown function (register_shutdown_function()) will not be called when the user disconnects, and the process will keep running in the background, waiting for input. I know of no way around this, besides using some other means of IPC.
richard dot quadling at carval dot co dot uk
04-Feb-2004 08:04
The issue involving some sites requiring a valid user-agent string when using fopen can easily be resolved by setting the user_agent string in the PHP.INI file.

If you do not have access to the PHP.INI file, then the use of

ini_set('user_agent','Mozilla: (compatible; Windows XP)');

should also work.

The actual agent string is up to you. If you want to identify to the sites that you are using PHP ...

ini_set('user_agent','PHP');

would do.

Regards,

Richard Quadling.
29-Jan-2004 02:34
If you are connecting to your ftp server through a router doing NAT (such as the Zyxel 128L prestige router/bridge we are using) by doing say an <? fopen("ftp://ftpusername:ftppassword@ftpserver/".$file_name, "w") ?>, then this could fail. You will get php_hostconnect connection failed error. This is because <?fopen() ?>function uses a passive ftp connection which the Zyxel router does not support, even though your ftp server may be configured to allow the passive connections which php <?fopen?> function is using. Note that $file_name is the file we want to ftp to the remote server eg could be file.txt.

Thus an alternative would be to do create the file you want in a local directory of your machine or in the webserver where your php files reside eg use <?fwrite()?> as documented in the manual. Once you have the $file_name you want to ftp created, do the following:

<?
ftp_connect
($ftp_server);
//which can connect to the ftp server using an active connection.
ftp_login ($conn_id, $ftp_username."@".$ftp_server, $ftp_password);
$fp = fopen($PATH."".$file_name, 'r');
// eg. $fp = fopen("http://www.yourwebsite.com/".$file_name, 'r');
//turn off passive mode transfers
ftp_pasv ($conn_id, false);
//now upload $file_name
ftp_fput($conn_id, $file_name, $fp, FTP_ASCII));
?>
Your file should now be in your ftp server, having used an active connection.
sergiopaternoster at tiscali dot it
27-Nov-2003 08:11
If you want to open large files (more than 2GB) that's what I did and it works: you should recompile your php with the CFLAGS="-D_FILE_OFFSET_BITS=64" ./configure etc... This tells to your compiler (I tested only gcc on PHP-4.3.4 binary on Linux and Solaris) to make the PHP parser binary large file aware. This way fopen() will not give you the "Value too large for defined data type" error message.
God bless PHP
ciao
Sergio Paternoster
ken dot gregg at rwre dot com
25-Nov-2003 06:03
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:

$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.
dan at cleandns dot com
19-Nov-2003 02:15
<?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";

?>
Bill Fletcher
18-Nov-2003 01:33
I had the same problem mentioned by Tim Fountain below:  trying to open a file larger than 2 GB to read it throws the error "Value too large for defined data type" .  (This error is explain in the online manual under filesize(), but no workaround for OPENING files is given.)

After lots of Googling (mainly to unanswered forum questions) I found a workaround on a Perl forum:
open a pipe to "cat filename":

  $fh = popen("cat $filename", "r");

Hope this saves someone some of the grief I've just gone through!

Bill
phpNO at SPAMperfectweb dot com
31-Jul-2003 04:39
I offer the following script for updating a counter, using methods gleaned from various posts on file operations...

<?
$counter_file
= 'somefile.txt';
clearstatcache();
ignore_user_abort(true);    ## prevent refresh from aborting file operations and hosing file
$fh = fopen($counter_file, 'r+b');    ## use 'r+b' so file can be read and written
if ($fh)
{
     if (
flock($fh, LOCK_EX))    ## don't do anything unless lock is successful
    
{
        
$count = fread($fh, filesize($counter_file));
        
rewind($fh);
        
$count++;
        
fwrite($fh, $count);
        
fflush($fh);
        
ftruncate($fh, ftell($fh));    ## better than truncating to 0 before writing, per 04-Mar-2003 comment below
        
flock($fh, LOCK_UN);
     } else echo
"Could not lock counter file '$counter_file'";
    
fclose($fh);
} else  echo
"Could not open counter file '$counter_file'";
ignore_user_abort(false);    ## put things back to normal

echo "counter is at $count";
?>
unshift at yahoo dot com
01-Jul-2003 07:58
It seems that fopen() errors when you attempt opening a url starting with HTTP:// as opposed to http:// - it is case sensitive.  In 4.3.1 anyway..."HTTP://", by not matching "http://" will tell the wrapper to look locally.  From the looks of the source, the same goes for HTTPS vs https, etc.
simon at gornall dot net
19-Jun-2003 03:24
If you're having problems with fopen("url...") but you can run 'host url' in a shell window and get the correct lookup, here's why...

This has had me banging my head against it all day - finally I found the answer buried in the bug reports, but figured it should really be more prominent!

The problem happens when you're on an ADSL line with DHCP (like our office)... When the ADSL modem renews the DHCP lease, you can also switch DNS servers, which confuses apache (and hence PHP) - meaning that you can't look up hosts from within PHP, even though you *can* from the commandline.... The short-term solution is to restart apache.

You'll get "php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution in ..." messages as symptoms. Restart apache, and they're gone :-)

Simon
RobNar
17-Jun-2003 11:15
This is an addendum to ibetyouare at home dot com's note about Apache directory permissions.  If you are on a shared host and cannot tweak Apache's permissions directives then you might try setting the same thing in a .htaccess file.  Failing that, if you are having trouble just creating files then  set the directory permissions to allow writing (for whatever directory the file is supposed to be in) and include the following before fopen():

`touch /path/to/myfile/myfile.txt`;

That will usually create a new empty file that you can write to even when fopen fails. - PHP 4.3.0
09-Jun-2003 06:50
If you have problems with safe mode creating errors

"Warning: SAFE MODE Restriction in effect. The script whose uid is.."

because one of your PHP scripts created the PHP file you are now trying to run, then you can use fopen() to create these files which will then be owned by you (not the server admin).

It must be done using the ftp method...

>> fopen('ftp://user:pass@domain.com', 'w+b');

But please remember that this only creates files, I haven’t found a way around setting the correct UID on folders (yet)

Krang
- http://www.krang.org.uk
Jhilton a at t nurv dot us
05-Jun-2003 03:54
Quick tip. If using fopen to make http requests that contain a querystring, it is advised that you urlencode() your values, else characters like @ can make fopen (or whatever wrapper it is using) throw an error.
Tim Fountain
30-Apr-2003 07:43
There seems to be an upper limit on the size of file that can be opened - when trying to open a ridiculously large file (~2.5gig) I got a 'file to large' error, and fopen returned false.  This doesn't seem to be documented anywhere and there's no obvious way to change the limit.  Obviously opening very large files isn't something you want to do very often but it's worth keeping in mind.
04-Mar-2003 11:49
To overwrite a file with a new content without deleting it, and without changing the owner or access rights, it's best to not use:

$file = fopen($filename, 'r+b); // binary update mode
...
ftruncate($file, 0);
fwrite($file, $my_stuff);
...
fclose($file);

but instead the faster one:

$file = fopen($filename, 'r+b); // binary update mode
...
rewind($file);
fwrite($file, $my_stuff);
fflush($file);
ftruncate($file, ftell($file));
...
fclose($file);

The reason is that truncating a file at size 0 forces the OS to deallocate all storage clusters used by the file, before you write your content which will be reallocated on disk.

The second code simply overwrites the existing content where it is already located on disk, and truncates any remaining bytes that may exist (if the new content is shorter than the old content). The "r+b" mode allows access for both read and write: the file can be kept opened after reading it and before rewriting the modified content.

It's particularly useful for files that are accessed often or have a size larger than a few kilobytes, as it saves lots of system I/O, and also limits the filesystem fragmentation if the updated file is quite large.

And this method also works if the file is locked exclusively once opened (but I would rather recommend using another empty file for locking purpose, opened with "a+" access mode, in "/var/lock/yourapp/*" or other fast filesystems where filelocks are easily monitored and where the webserver running PHP is allowed to create and update lock files, and not forgetting to close the lock file after closing the content file).
draconumpb at hotmail dot com
06-Dec-2002 06:37
I just used explode() as an alternative to fscanf, since my only delimiter was | (pipe). I was having problems with it, since I use it in my news-management script. I found that it cut the last variable I was using, $body, a bit short when I posted a long news post. This would've been a real problem for anybody trying to make news posts longer than a paragraph or so.

However, I found that when I used:
list($variable1, $variable2, etc) = explode("|",$data);
it didn't cut any variables short, so.. what I'm really trying to say here is that for people who are experiencing problems with parsing simple files (i.e with only a single, simple delimiter such as : or |) using the unecessarily complex fscanf() and sscanf() functions, explode() is definately the way to go.

function get_news($filepath, $newsid)
{
$datafile = fopen("$filepath/news/$newsid.txt","r");
$data = fread($datafile, 1000000);
list($author, $email, $date, $subject, $body) = explode("|",$data);
$body = stripslashes("$body");
$subject = stripslashes("$subject");
echo "<a href=\"mailto:$email\">$author</a> -- $date -- $subject<hr>$body<p>";
}

sample file:

AdministratorMax|admin@somesite.com|Tuesday, March 5th @ 5:45 PM EST|Site Going Down Tomarrow|Well, folks, I\'m sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.

Output:

<a href="mailto:admin@somesite.com">AdministratorMax</a> -- Tuesday, March 5th -- Site Going Down Tomarrow<hr>Well, folks, I'm sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.

Thought that might be useful for anybody making a simple news-management script, ;)

By the way, feel free to correct me if I made any mistakes - I'm at my dad's work where I don't really have a way to check to see if it works or not. However, I use a more complex version of this on my portal project, and it works beautifully.
Jester at free2code dot net
28-Nov-2002 12:13
Having trouble with file operations in PHP? Try this:
http://www.free2code.net/tutorials/programming/php/4/file2.php

Explains opening files in different modes as well as reading from and writing to files.
andyNO at SPAMuchicago dot edu
30-Aug-2002 05:42
Playing with fopen("https://xxx", "r") it seems that HTTPS is only supported with OpenSSL AND PHP 4.3 . Older versions of PHP don't seem to be able to do this.
suraj at _nospam_nospam_symonds dot net
17-Jul-2002 09:41
This note is relevant to the first few notes that talk about writing to files as user 'foobar'.

if one wanted to write to files as user 'foobar' when apache runs as 'root' the new POSIX fucntions. Here's a code snippet explaining how this can be done

<?

$x
= posix_getuid ();

if (
0 == $x) {
   echo
"I'm root\n";

  
$pw_info = posix_getpwnam ("foobar");
  
$uid = $pw_info["uid"];
  
posix_setuid ($uid);

  
$fp = fopen ("/tmp/test.file", "w");
  
fclose ($fp);
} else {
   echo
"I'm not root! I'm not worthy... I'm not worthy....\n";
}

?>

[Note:
1. This would only set the uid... not the gid. If you wanted to write to files as 'foobar:foobar' then you also have to do a posix_setgid ($gid);
2. If you are using the CGI version of php4, you should setuid your php4 interpreter: chmod 4755 /path/to/cgi-bin/php4 (generally, /usr/lib/cgi-bin/php4)]
01-Jul-2002 12:57
Note that if specifying the optional 'b' (binary) mode, it appears that it cannot be the first letter for some unaccountable reason. In other words, "br" doesn't work, while "rb" is ok!
jared at dctkc dot com
22-Apr-2002 04:33
<?php
// HOW TO USE PHP TO WRITE TO YOUR SERIAL PORT: TWO METHODS
$serproxy=true;
if (
$serproxy) {
  
// Use this code in conjunction with SERPROXY.EXE
   // (http://www.lspace.nildram.co.uk/freeware.html)
   // which converts a Serial stream to a TCP/IP stream
  
$fp = fsockopen ("localhost", 5331, $errno, $errstr, 30);
   if (!
$fp) {
       echo
"$errstr ($errno)";
   } else {
      
$e = chr(27);
      
$string  = $e . "A" . $e . "H300";
      
$string .= $e . "V100" . $e . "XL1SATO";
      
$string .= $e . "Q1" . $e . "Z";
       echo
$string;
      
fputs ($fp, $string );
      
fclose ($fp);
   }
} elseif (
$com1) {
  
// Use this code to write directly to the COM1 serial port
   // First, you want to set the mode of the port. You need to set
   // it only once; it will remain the same until you reboot.
   // Note: the backticks on the following line will execute the
   // DOS 'mode' command from within PHP
  
`mode com1: BAUD=9600 PARITY=N data=8 stop=1 xon=off`;
  
$fp = fopen ("COM1:", "w+");
   if (!
$fp) {
       echo
"Uh-oh. Port not opened.";
   } else {
      
$e = chr(27);
      
$string  = $e . "A" . $e . "H300";
      
$string .= $e . "V100" . $e . "XL1SATO";
      
$string .= $e . "Q1" . $e . "Z";
       echo
$string;
      
fputs ($fp, $string );
      
fclose ($fp);
   }
}
?>
15-Mar-2002 09:18
Also if you're server is useing htaccess to authticate users make sure to add the username and password to the http link you're trying to open. I forgot about this and took a while to find.
ie:

fopen("http://user:pass@www.mysite.com/mypage.php");
landrews at email dot com
21-Feb-2002 01:31
To the people haveing problems with opening "ftp:" url opens and files not being written.  It seems that PHP wants the complete path. Make sure your not referencing through a soft link or alias. Use the full path from /
ie
/usr/www/htdocs/data/blah.php
mp3godNOSPAM at mail dot ru
30-Jan-2002 06:12
previous notes about using fopen via proxy didn't work for me. so i've written some code, i hope it'll be useful for someone

function fget_proxy($url)
{

 $PROXY_URL="proxy.yourisp.org";
 $PROXY_PORT=8080;

 putenv("http_proxy=$PROXY_URL:$PROXY_PORT");
 $result = shell_exec("wget -q -O - $url");
 
 return $result;
}
slevy1 at pipeline.com
29-Dec-2001 09:54
Attn Perl Programmers:

If you are used to writing script like
 
do something || die("no can do");

note that in php || has a higher precedence than =

So, don't write:

$h = fopen("$filename", "r") || die("cannot open $filename");

b/c this will overwrite the file ptr!

Now, or has a lower precedence than || and is also lower than =

So, you may write:

$h = fopen("$filename","r") or die("cannot open $filename");

However, you may avoid the entire issue with code like this:


$h = fopen("$filename","r");
if (!$h) {
   die("unable to open $filename");
}
php at themastermind1 dot com
24-Oct-2001 01:37
I have found that I can do fopen("COM1:", "r+"); to open the comport in windows. You have to make sure the comport isn't already open or you will get a permission denied.

I am still playing around with this but you have to somehow flush what you send to the comport if you are trying to communicate realtime with a device.
keithm at aoeex dot NOSPAM dot com
31-Jul-2001 08:19
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);
?>
ibetyouare at home dot com
26-Jul-2001 04:26
Ok guys just to make a note here. If you are attempting to create a file in a directory, first makes sure you have read/write permissions on that directory.
If you do, check your apache config to make sure you are allowing directory write permissions.
It can be a silly mistake that can cost you a lot of headaches.
defdac at hotmail dot com
22-Jan-2001 04:41
Newbie advice: The little "b" for binary operations is very essential when working with PHP4 and Apache on the win32 platform. fread() only reads a couple of hundred bytes when reading for example an image without "b".
// Read tempfile data into $thumb_img.
$thumb_file_size = filesize('C:\\Temp\\temp.jpg');
$fp = fopen('C:\\Temp\\temp.jpg', "rb");
$thumb_data = addslashes (fread ($fp, $thumb_file_size));
fclose ($fp);
unlink('C:\\Temp\\temp.jpg');
icon at mricon dot com
09-Nov-1999 05:44
If you're running PHP as apache module, it will always write files as "nobody", "www", "httpd", (or whatever user your webserver runs as) unless you specify a different user/group in httpd.conf, or compile apache with suexec support.
However, if you run PHP as a CGI wrapper, you may setuid the PHP executable to whatever user you wish (*severe* security issues apply). If you really want to be able to su to other user, I recommend compiling with suexec support.
AFAIK, PHP can't NOT use SuEXEC if apache does. If PHP is configured as an apache module it will act as whatever user the apache is. If apache SuEXEC's to otheruser:othergroup (e.g. root:root), that's what PHP will write files as, because it acts as a part of apache code. I suggest you double-check your SuEXEC configuration and settings. Note: you can't su to another user within the PHP code -- it has to be an apache directive, either through <VirtualHost>, or through .htaccess. Also note: I'm not sure how it all works (if it works at all) on Win32 platforms.
Check www.apache.org to see how it's done.

<fnmatchfpassthru>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT