I've spent a lot of time lately dealing with a little known, under-documented but extremely useful class in WordPress called WP_Filesystem. WP_Filesystem is used throughout WordPress to handle core/plugin/themes updates and various tasks that require writing files to your webserver.
The WP_Filesystem class is a base class that has many extensions depending on what 'method' it can use to do the work it needs to do (install a plugin, upgrade core, move a file, etc.). There are many methods that WP_Filesystem can utilize based on your server setup and permissions:
- FTP Sockets
The beauty of how the WP_Filesystem class works is that it chooses the best option based on the user's setup, AND it makes sure that file ownership is correct before it performs any actions. It's a win-win for everyone.
WordPress provides a nifty function called request_filesystem_credentials() that does all the hard work for you in setting up WP_Filesystem.
The request_filesystem_credentials() function accepts 5 parameters:
$form_post is the URL in which the resulting form should be posted to. Security is always an issue, so you should be using wp_nonce_url() to build this URL, where the nonce field matches the nonce in the submitted form field. You can easily pass along extra query args here as well using add_query_arg().
$method is the method in which you want WP_Filesystem to use. Because WP_Filesystem automatically determines and populates the best method for use, there's really no need to specify a particular method here unless you are doing it for testing purposes. A good use-case would be to force a particular method and ensure that WP_Filesystem will write files to your webserver correctly if it can't verify the ownership of files.
$error is a boolean to specify whether you want to output an error message if WP_Filesystem fails to connect. It is false by default, but can be helpful to turn on for testing and debugging.
$context is the directory in which you want to test WP_Filesystem so that it can verify ownership of files. By default, it will attempt to write a temporary file to the wp-content directory (specified by the constant WP_CONTENT_DIR). This field can be useful if you want to test the particular directory in which you are about to write files.
$extra_fields are extra $_POST fields from the previous form that should be included in the resulting post form. The $_POST fields must be strings (arrays are not currently accepted - see this ticket for more info).
Now that we have dissected request_filesystem_credentials(), let's put it into action.
You must be logged in and have an active premium membership to view the rest of this content. Register or login from the sidebar.