In the script below, I need to convert the readfile to the WP_filesytem equivalent. However, I can’t find same in Codex. Any help much appreciated.
This script saves the settings.ini file to the user’s desktop/pc.
WP_Filesystem();
global $wp_filesystem;
$mySettingsFileLocation = WP_PLUGIN_DIR.'/my-settings/settings.ini';
if ( ! $wp_filesystem->put_contents( $mySettingsFileLocation, $mySettings, 0644) ) {
return true;
}
// Define the path to file
$file = WP_PLUGIN_DIR.'/my-settings/settings.ini';
if(!$file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=settings.ini");
header("Content-Type: application/ini");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}
Reading a file to send to the user is perfectly safe and does not necessarily need to be converted to the WP_Filesystem methods. Only writing is potentially an issue.
However, if you wanted to do so, this would be the equivalent:
echo $wp_filesystem->get_contents( filename variable here );
Also, note that your filename for “put_contents” is incorrect. Instead of using
WP_PLUGIN_DIR
, you need to use$wp_filesystem->wp_plugins_dir()
because the “remote” directory might not be the same as the “local” directory.$mySettingsFileLocation = $wp_filesystem->wp_plugins_dir() . '/my-settings/settings.ini';