Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FileHandle's

Status
Not open for further replies.

skottieb

Programmer
Jun 26, 2002
118
AU

Can anyone tell me what is wrong with this code:

if ($fp = fopen($users, "a+") != NULL ){
fputs($fp, "$email \n$name\n\n",'');
fclose($fp);
}

The file gets created in the fopen call so the if block executes
My browser ouputs this:

Supplied argument is not a valid File-Handle resource..>
twice for each call to the handle, (fputs and fclose).

All help greatly appreciated


skottieb:)
 
The problem is you're not taking into account operator precedence.

You're testing if
fopen($users, "a+") != NULL
which returns a true or a false
You're then assigning this to
$fp

true/false is not a valid file handle.

Try

Code:
if (($fp = fopen($users, "a+")) !== NULL) {

(I used the strict comparison for the boolean, you can certainly stick with != NULL if you prefer)

-Rob
 
Oh, as a side note, your first comparison also returns true no matter what... since it will always be able to assign true or false to fp.

-Rob
 
Oh, and I almost missed it, but you have a '' as the third parameter to fputs()... that is incorrect.. you should only send 2 parameters unless you're going to specify the length. As you have it, you're effectively submitting a length of 0 so it won't actually write anything to the file.

-Rob
 
I'm afraid to post -- I might interrupt skiflyer....


skottieb:
In addition to skiflyer's copious comments, from a general maintainability point of view,

Code:
$fp = fopen($users, "a+");
if ($fp != NULL ){
     fputs($fp, "$email \n$name\n\n",'');
     fclose($fp);
}

is more readable than your version, and thus easier to maintain.

Want the best answers? Ask the best questions: TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top