PDA

View Full Version : File Writing Problems



JonnyH
October 19th, 2007, 17:05
I've been making a script in the admin panel which lets you edit files in the style, so yeah. I've done it all but when you submit to edit, it doesn't do it and comes up with my error message saying there's been a problem. Heres the code which edits the file:


//Edits a file
function edit_file($link,$value) {
if (file_exists($link)) {
$fh = fopen($link,'w');
if(fwrite($fh,$value)) {
fclose($fh);
return true;
}
}
elseif(!file_exists($link)){
return false;
}
}

The code which calls it:


if($this->edit_file("../style/".$this->style."/$name", $_POST['file'])) {
$this->errors("Your file has been successfully edited");
$this->done();
}
else {
$this->errors("There's been a problem while editing your file");
$this->done();
}

EDIT: I've debugged the script and it's returning false on the fwrite function not if it exists.

Yun
October 20th, 2007, 00:04
"if (fwrite($fh, $somecontent) === FALSE) {"

Or just copy the function used on www.php.net, you can't go wrong with that.


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";
}

By the way,
elseif(!file_exists($link)){ seems redundant. Just change it to an else.

JonnyH
October 20th, 2007, 03:29
Worked, thanks.