Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the file I am attempting to write "non-existing"?

I have a custom config file in my CI application. In my web application's admin panel, I want to have a form that I can use to change the values of the config array of the custom file. My problem right now is that the write_file function always returns false and I don't know why. I am pretty sure I am writing the path in the function correctly and the config directory is not read-only(this is wamp, so windows). The file definitely exists. What am I doing wrong?

This is application/controllers/config/assets.php

$file = FCPATH . 'application\config\assets_fe.php';
if(is_writable($file)) {
    $open = fopen($file, 'W');
    if(!fwrite($open, $frontend)){
        echo "Could not write file!";
    } else {
        echo "File written!";
    }
} else {
    echo "File not writable!";
}

This is a screenshot of the file in it's location in windows explorer. config folder

I have tried the following file paths in the write_file function:

write_file(FCPATH.'application/config/assets_fe.php', $frontend, 'W');
write_file('application/config/assets_fe.php', $frontend, 'W');
write_file('./application/config/assets_fe.php', $frontend, 'W');

None of the above file paths have worked... could it be something else?

FYI: FCPATH = 'W:\wamp\www\zeus\' and it's defined by CI's front controller to return the path of that file.

Update: I tried using just the native PHP version and it's saying that the file or directory does not exist. Maybe I am using the wrong path. What should it be?

like image 243
ShoeLace1291 Avatar asked Dec 15 '14 04:12

ShoeLace1291


1 Answers

The answer is simple, you are passing an invalid mode, captial W, to fopen. It should be a lowercase w. So what's happening is fopen is returning false, then you're passing that to fwrite instead of a resource, causing it to return false.

Just change

$open = fopen($file, 'W');

to

$open = fopen($file, 'w');

You might also test the result of fopen

if(!$open)
    echo 'Could not open file';

You could also try file_put_contents since you don't do anything else w/ the file handle.

$file = FCPATH.'application\config\assets_fe.php';
if(is_writable($file)){
    if(!file_put_contents($file, $frontend)) {
        echo "Could not write file!";
    } else {
         echo "File written!";
    }
} else {
    echo "File not writable!";
}
like image 74
quickshiftin Avatar answered Nov 03 '22 01:11

quickshiftin