I'm generating a very useful .dat file, but I read that file_put_contents if frowned upon and that WP_Filesystem should be used instead.

I see no methods to take dynamic input and create a file and then upload it to a directory of my choice at all.

What functions out of it should I look for?

My exact flow is: User clicks a button (the call is AJAX'd) and then 3 files are generated and put inside my directory. As of now, this is how the "save file" function looks like:

$contents = ob_get_clean();
\file_put_contents( THEME_DIR . '/dump/test.dat', $contents );

1 Answer 1


Seems like you have several misconceptions/misunderstanding about when/why and how you should write to files.

  1. In general never write to any directory in which code resides, either core code or themes and plugins code. Those directories might be shared between different wordpress instances, and therefor they are not appropriate to be used for data related to only one instance.

  2. WP_Filesystem Needs to be used when you need to write to a directory to which you will normally not have write permission (which in a secure wordpress install will be all directories except for uploads), and therefor you need to ask a user for credentials to use when trying to write files (underlying tech is usually FTP). This means that it has to be a user initiated process and not applicable to anything running as cron task. It is also a very ugly UX.

You might be tempted to store user credentials for this but this is a security bad practice. Once credentials are in the DB or disk, any bad actor that succeeded to convince the site owner to upload his plugin can own the site.

  1. You should write only to the uploads directory in which case it does not make any difference which API you use as they are both equivalent.

So write only to the uploads directory, and just use file_put_contents for that, not reason to use anything more complex. If you have some secret data that you do not think belongs to a public place, first ask yourself why do you need to store it at all (if for example you generate CSV, can't you just generate it on the fly?), and if you must, just use a hard to guess file name and set the htacceess for the directory to indicate to the web server that it is a non publicly available directory.

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.