Writing to a file from my WordPress plugin

I wrote my own plugin for my WordPress site, which relies on reading / writing from the xml data file in the plugin folder. When I test this standard PHP code for reading / writing files, it will allow me to create / write files located at the wp-admin / level, but not the files in the plugin folder, although it can read both.

$file = 'test.xml'; (Can write to this file) $file = plugins_url()."/my-plugin/test.xml"; (Can read but not write to this file) // Open the file to get existing content $current = file_get_contents($file); echo $current; // Append a new person to the file $current .= "<person>John Smith</person>\n"; // Write the contents back to the file file_put_contents($file, $current); 

I get the following debugging error:

Warning: file_put_contents (HTTP: //localhost/wp_mysite/wp-content/plugins/my-plugin/test.xml) [function.file-put-contents]: could not open the stream: HTTP wrapper does not support write connections to / Applications / MAMP / htdocs / wp _mysite / wp-content / plugins / my-plugin / my-plugin.php on line 53

I am currently running this from a local MAMP server, but I want a solution that allows me to package and publish the plugin on any WordPress server. What is the right approach?

Thanks -

+7
source share
1 answer

Do not access it through HTTP if you want to write to a file. Get access to it directly, instead of reading and writing as quickly as possible and the most direct way to access the file.

To get the path to the directory of the base plugin, use the constant WP_PLUGIN_DIR :

 $file = 'test.xml'; // (Can write to this file) $file = WP_PLUGIN_DIR."/my-plugin/test.xml"; // ^^^^^^^^^^^^^ 

This will not allow you to use HTTP, which should not be used at all due to performance reasons and because HTTP does not support writing. But first of all, since this is a file on the server that you have access to, access it directly.

+10
source

All Articles