Home » Php » php – Why is the file I am attempting to write "non-existing"?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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!";
}

Answer:

You have to use set_item to write into config file.

$this->config->set_item('item_name', 'item_value');

for arrays:

$this->config->set_item('ftp_frontend', array(...));

Its here in config.

Answer:

I don’t think you need to write in config.php file. Instead of writting in config.php file, you can user CI configuration class to override value of config file like below

For single item

$this->config->set_item('item_name', 'item_value');

For array item

$this->config->set_item('item_array', array(...));