Saving files in WordPress using the Filesystem_API

When building plugins or addons, sometimes we need to save custom files within WordPress.

These can be custom JavaScript or CSS files that a user edited and are loaded to override core functionality.

In most cases inline styles and scripts are an option, but not always the most elegant way. Everyone has to decide that for themselves. (wp_add_inline_style) Not talking about performance between inline and external files here :)

Another option is the wp_head action:

  1. add_action('wp_head','hook_css');
  2.  
  3. function hook_css(){
  4. $output="<style> .wp_head_example { background-color : #f1f1f1; } </style>";
  5. echo $output;
  6. }

WHERE

Many ask where can or should I save files created within a plugin.

  1. In the plugin folder ? Bad idea,  as that folder will be deleted on each upgrade of the plugin.
  2. In a separate plugin, just for those extra files. That is an option, but many webmasters prevent writing to any other folder than the upload folder. Also adding a blank plugin to just add upload folders is not really optimal.
  3. In the upload folder itself. Just like the name says, its the main folder to upload files to!

SECURITY

When dealing with file creation and uploads, security is always important. That relates to any other platform doing similar operations. A folder created within a plugin directory is not less or more secure than a folder created in the upload directory.

Its important to have the correct file and folder permissions set:

  1. Files should have permissions not higher than 664 (start at 644)
  2. Directories should have permissions not higher than 755 (start at 744) Try what works. The lower the more secure :)

There is a detailed article about permissions over at WordPress as well.

When it comes to creating files in PHP the term cross-site-scripting often comes up. When the system creates a file it is owned by the webserver and on a shared hosting account those files could be altered by another user on the same webserver. This could allow them to inject malicious code and compromise your sever.

That is why the WP_Filesystem was created, to make things more secure and make sure that the owner of files is correct.

CREATING FILES

WordPress provides a nice clean interface to create folders and save files to the upload folder. Here a simple example from one of my current projects.

Prepare the filesystem

  1. require_once( ABSPATH . 'wp-admin/includes/file.php' );
  2. global $wp_filesystem;

Get upload dir information and prepare directory to save to

  1. $upload_dir = wp_upload_dir();
  2.  
  3. $dir = trailingslashit( $upload_dir['basedir'] ) . 'your folder/';
  4.  

Check if file exists, create folder, delete similar and save.
In my case I am adding a custom key and the page id to the file.

  1. $key = md5($js);
  2.  
  3. if (!is_file($dir."/subfolder/yourfile_" . get_the_ID() . "_" . $key . ".js")) {                               
  4.    
  5.     WP_Filesystem();
  6.     // Create main folder within upload if not exist
  7.     if(!$wp_filesystem->is_dir($dir) )
  8.     {
  9.         $wp_filesystem->mkdir( $dir );
  10.     }
  11.     // Create a subfolder in my new folder if not exist
  12.     if(!$wp_filesystem->is_dir($dir."/subfolder") )
  13.     {
  14.         $wp_filesystem->mkdir( $dir."/subfolder" );
  15.     }
  16.     // Delete similar files, might not apply to you
  17.      foreach (glob($dir . "/subfolder/yourfile_" . get_the_ID() . "_*.*") as $filename) {
  18.         unlink($filename);
  19.     }  
  20.     // Save file and set permission to 0644
  21.     $wp_filesystem->put_contents( $dir."/subfolder/yourfile_" . get_the_ID() . "_" . $key . ".js", $js, 0644 );
  22.    
  23. }

If the direct way is not possible, you can also use or force the FTP approach
(request_filesystem_credentials).

This will check for the ftp credentials and request them with a form if needed.

  1. if ( ! WP_Filesystem($creds) ) {
  2.       request_filesystem_credentials($url, $method, true, false, $form_fields);
  3.     return true;
  4. }
  5.  

This is just a very rough outline of how to do it, but should get you started.

Enjoy coding …

 

Alex

I am a full-stack developer. I love programming,  design and know my way around server architecture as well.  I would never feel complete, with one of these missing. I have a broad range of interests, that’s why I constantly dive into new technologies and expand my knowledge where ever required. Technologies are evolving fast and I enjoy using the latest. Apart from that, I am a peace loving guy who tries to have people around him that think the same.  I truly believe in the principle: “If you help someone, someone will help you, when you need it."

Recent Posts

B&B / Hotel Booking Solutions for WordPress | 2024

BOOKING SOLUTIONS 202x This is my take on a subset of booking, appointment, PMS or… Read More

4 weeks ago

WordPress Cron + WP-CLI + Ntfy

THE GOAL Create a system cron for WordPress, that is accessible and can be easily… Read More

2 months ago

2024 is here and now :)

2024, what's cooking? Slowly getting into the 2024 spirit. 3 projects coming to a close… Read More

4 months ago

2023 ends and whats next !

Short look back at 2023 This has been a busy and interesting year. I am… Read More

4 months ago

cubicFUSION Grid Tweaker – Elementor Grid made easy.

Elementor Pro provides grid containers as an experimental feature. The options provided are limited, when… Read More

5 months ago

Archaeology Travel Booth – Travel Innovation Summit 2023

Archaeology Travel is an online travel guide for people who enjoy exploring the world’s pasts.… Read More

6 months ago