Jump to content

fopen, fwrite, fclose ++ whats with the handle


etnastyles

Recommended Posts

Hello,

 

I am wanting to create a new file on my server using the below file functions,

one thing im not 100% on is the $handle var.

 

why open a $handle to a file that dosnt exist on the server???

 

i see the below as open a handle to a file with name that i specify

then write to the file + add my data then close the file..

 

could you ignore the open bit (fopen)

 

code:

-------------------------------------------------------------------------------------

$handle = fopen($sourcefilename, 'x+');

fwrite($handle, $stringData);

fclose($handle) or die ("error closing handle. see admin..");

-------------------------------------------------------------------------------------

 

Link to comment
Share on other sites

The handle variable is what PHP uses as a pointer to the file. If the file doesn't exist and you use the correct mode when you open it, the file will be created.

 

BTW, you really should have the "or die" clause on the fopen, not the fclose.

<?php
$handle = fopen($sourcefilename,'x+') or die("Could not open the file $sourcefilename, see admin...");
?>

 

Also, you can use any variable name, not just $handle. I use $fp, for "file pointer".

 

Ken

Link to comment
Share on other sites

i was going to ask about the error checking :)

 

the file isnt even created yet so do i need the or die() because it dosnt exist..

wont this just fail.

 

code:

----------------------------------------------------------------------------

$handle = fopen($sourefilename, 'x+') or die("Could not open the file $sourcefilename, see admin...");

----------------------------------------------------------------------------

Link to comment
Share on other sites

If you had read the manual page for the fopen() function, you should have seen the following explanation for the "x+" mode:

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.

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.