1

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?

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) { } 
} }
2
  • what have you done to debug? Commented Oct 27, 2013 at 16:53
  • I've confirmed that I'm getting expected results all the way up to the put_contents() call (by outputting the results to the screen). I'd welcome any suggestions you have.
    – Scott B
    Commented Oct 27, 2013 at 17:07

2 Answers 2

2

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.

1

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.

1
  • Thanks for the tip. I've updated my question with the results of the var_dump.
    – Scott B
    Commented Oct 27, 2013 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.