Converting fopen/fwrite operations to WP_filesystem

In the function below, I’m trying to convert the fopen/fwrite/fclose methods to the preferred WP_filesystem methods. Everything works as expected using the commented out script block, however, the WP_filesystem methods always return the error block.

Any ideas what I’m doing wrong?

Read More
function so_doHtaccess(){
if ( !current_user_can( 'manage_options' ) ) return;

    if ( file_exists( get_home_path() . ".htaccess" ) ) {
        $htaccess_file = get_home_path() . ".htaccess";
        $htaccessnew   = get_option('my_updated_htaccess');

/*
        if ( is_writeable( $htaccess_file ) ) {
            $f = fopen( $htaccess_file, 'w+' );
            fwrite( $f, $htaccessnew );
            fclose( $f );
        }
*/
            WP_Filesystem();
            global $wp_filesystem;

            $f = $wp_filesystem->get_contents($htaccess_file);

            if ( ! $wp_filesystem->put_contents( $f, $htaccessnew, 0644) ) {
                echo "There was an error saving the htaccess file. As a result no changes were made";die;
            }

    }

return;

}

When I var_dump($wp_filesystem) it yields:

object(WP_Filesystem_Direct)#358 (4) { 
["verbose"]=> bool(false) ["cache"]=> array(0) { } 
["method"]=> string(6) "direct" 
["errors"]=> object(WP_Error)#361 (2) { 
    ["errors"]=> array(0) { } 
    ["error_data"]=> array(0) { } 
} }

Related posts

2 comments

  1. The get_contents function returns the contents of the file, not a file handle. Using put_contents with $f after that is incorrect.

    Try $wp_filesystem->put_contents( $htaccess_file, $htaccessnew, FS_CHMOD_FILE ) instead.

    Also, it’s not necessarily safe to use things like “get_home_path” and such with the WP_Filesystem. The remote path may not match the local path. You’ll need to do something like this:

    $homedir = $wp_filesystem->abspath();

    To get the equivalent of the ABSPATH on the other filesystem.

  2. I expect that the problem is with the login credentials. Your code assumes that the credentials are set but you have done nothing to ensure that. var_dump($f) and see if you have an error object at $f->errors. That is, do this:

    $f = $wp_filesystem->get_contents($htaccess_file);
    var_dump($wp_filesystem);
    

    If you do have an error object you will need to rewrite your code that you request_filesystem_credential() if they are not already set.

Comments are closed.