PDA

View Full Version : fopen/fwrite woes


gnorty
10-14-05, 05:09 PM
HI. I have been fighting all night to save a file to a directory on my site, and keep getting file errors (file not writable).

In desperation, I went back to basics and tried getting a simple example script to work straight from php.net, modifying it (I think) to work on my site. This still is not writing the file correctly. Here is the code I am trying to use, can anyone tell me where it is going wrong? In an effort to persuade the thing to work, the /thumbs directory is set 777.

<?php
$filename = '/www/d/o/domain.com/htdocs/thumbs/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";
}
?>

mitchind
10-14-05, 05:54 PM
In an effort to persuade the thing to work, the /thumbs directory is set 777.
Can't do that here - set to 755

Does the file exust? From the manual...
Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writeable.

gnorty
10-14-05, 06:51 PM
I have tried with the directory empty, and with dummy files in there (also set to 777)

I tried also relative paths, but nothing seemed to work.

In the mean time I found an even simpler test script which worked, and have modified that to do what I want, so it all works. I would still be interested academically to find out why the script in this thread fails, I imagine the script itself is OK or it woulkd have long ago been corrected on php.net, so I can only imagine it is the path, although similar paths have worked ok with such things as imagecreatefromjpeg etc.

Perms set back to 755 on all files (I am aware of the risk, but I needed to assure myself that it wasnt a perms problem, and the area I am working on is not linked from the main index.html so I figured a quick experiment was safe enough).

Anyway, the script proper is now working as required, and all is well so the immediate panic is over. Thanks for the reply all the same :D

mitchind
10-15-05, 12:39 AM
I quoted right from the manual for you - with your code, the directory can't be empty. The file HAS to exist beforehand.

At Powweb you can't set permissions to 777 if you want anything to work for you.

If it sounds like I'm repeating myself, ... I think I am