[clue-tech] I'm blind, or why is this PHP fwrite() failing?

Mike Benavides mikeb at wispertel.net
Tue Sep 27 20:53:49 MDT 2005


On Mon, 2005-09-26 at 16:37 -0600, David L. Anselmi wrote:
> I guess you figured this out, but since I didn't see a concise 
> explanation here's a try.  You made the same mistake that perl coders 
> make if they don't understand the difference between || and or.
> 
> Jed S. Baer wrote:
> >     $ptologfile = fopen('/tmp/contactlog.txt', 'a') || die ("Can't open
> > logfile");
> >     if (is_writable('/tmp/contactlog.txt')) echo '<b>Writeable</b><br>';
> >     $junk = 'junk';
> >     fwrite($ptologfile, $junk) || die ("Can't write to logfile");
> [...]
> > fwrite(): supplied argument is not a valid stream resource
> 
> This says that $ptologfile is bogus implying that fopen() failed, but 
> you tested it and it didn't.
> 
> If you look here http://us2.php.net/manual/en/language.operators.php you 
> see that = is lower precedence than ||.  That means that:
> 
>  > $ptologfile = fopen('/tmp/contactlog.txt', 'a') || die ("Can't open
>  > logfile");
> 
> assigns TRUE to $ptologfile, which is bogus for fwrite().
> 
> The correct way is:
> 
>  > $ptologfile = fopen('/tmp/contactlog.txt', 'a') or die ("Can't open
>  > logfile");
> 
> because or is lower precedence than =.
> 
> HTH,
> Dave
> _______________________________________________
Does sample code I found on the "new" PHP 5 site give some insight on
how the syntax of fwrite works?
http://www.zend.com/manual/function.fwrite.php
Example 1. A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

   // In our example we're opening $filename in append mode.
   // The file pointer is at the bottom of the file hence 
   // that's where $somecontent will go when we fwrite() it.
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }

   // Write $somecontent to our opened file.
   if (fwrite($handle, $somecontent) === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }
   
   echo "Success, wrote ($somecontent) to file ($filename)";
   
   fclose($handle);

} else {
   echo "The file $filename is not writable";
}
?>
-- 
Mike Benavides <mikeb at wispertel.net>

_______________________________________________
CLUE-tech mailing list
CLUE-tech at cluedenver.org
http://cluedenver.org/mailman/listinfo/clue-tech



More information about the clue-tech mailing list