Using fopen() to create new file - works for a few then just doesnt

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I am currently working on a content management system where a user can
fill in a form (title, keywords, link text etc. - all the initial
attibutes), which when submitted, will go onto create a web page.

The code is as follows:

$html = "<html>\n<body>\n<p>Hello World</p>\n</body>\n<html>";
$handle = fopen($_SERVER['DOCUMENT_ROOT']."/path/to/folder/".$filename,
fwrite($handle, $html);

Pretty basic, I think. I works for a few and then it just stops. I get
no error to say that 'could not create file' or 'file not found', it
just submits. Any reason for this? I have tried searching the C: drive
for the file but it cannot be found.

At the moment Im trying to figure out when it actually occurs but for
some annoying reason, it seems to be working now. I would prefer to be
assured that it wont occur again so just thought I would still post
something here just encase this problem is a known one.

Is fopen() the best solution for creating files? I was aware that it
was used to open an existing file but create one (?). Is this what it
was intended to do? Im sure it is, but its new to me.

Anyway, if anyone can offer any advice it would be much appreciated. Im
going to move onto another part until I resolve this bug. Thanks


Re: Using fopen() to create new file - works for a few then just doesnt wrote:

Quoted text here. Click to load it

Basically, turn on some good error reporting in your script. From the php  
example page:

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

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

} else {
 echo "The file $filename is not writable";


Site Timeline