
WordPress Filesystem API
- December 4, 2015
- Leave a comment
WordPress introduces Filesystem API which is used to read and write files securely. While working with files, developers usually face security and compatibility issues. WP_Filesystem is a wrapper around different approaches to collaborate with the filesystem in a protected way. It embodies file operations and it additionally preserves file ownership (in read and compose case).
The initial phase in utilizing the WP_Filesystem is asking for credentials from the user:
1 2 3 4 5 |
//URL of the page where page should be submitted $url = wp_nonce_url('themes.php?page=otpions','example-theme-options'); if (false === ($creds = request_filesystem_credentials($url, '', false, false, null) ) ) { return; // stop processing here } |
Before the WP_Filesystem can be utilized, it must be initialized with the proper credentials:
1 2 3 4 |
if ( ! WP_Filesystem($creds) ) { request_filesystem_credentials($url, '', true, false, null); return; } |
Once WP_Filesystem is initialized then you can use global $wp_filesystem. To write a file, you can use the following script:
1 2 3 4 5 6 |
global $wp_filesystem; $wp_filesystem->put_contents( '/tmp/example.txt', 'Example contents of a file', FS_CHMOD_FILE // predefined mode settings for WP files ); |
You can create directory by using WP_Filesystem:
1 2 3 4 5 6 7 8 |
/* replace the 'direct' absolute path with the Filesystem API path */ $plugin_path = str_replace(ABSPATH, $wp_filesystem->abspath(), MY_PLUGIN_DIR); /* Now we can use $plugin_path in all our Filesystem API method calls */ if(!$wp_filesystem->is_dir($plugin_path . '/config/') { /* directory didn't exist, so let's create it */ $wp_filesystem->mkdir($plugin_path . '/config/'); } |
You can also check if the content of file exists or not. If it exists, then you can read the content by using get_contents($folder_file) function:
1 2 3 4 5 6 7 8 9 10 |
/* read the file */ You can also read file by using WP_Filesystem //Folder path $folder_dir = WP_PLUGIN_DIR . '/filesystem-folder'; $folder_file = trailingslashit($folder_dir).'file.txt'; if($wp_filesystem->exists($folder_file)){ //check for existence $filetext = $wp_filesystem->get_contents($folder_file); if(!$demotext) return new WP_Error('reading_error', 'Error when reading file'); //return error object } |
User Comments