Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a file from my WordPress plugin

I've written a custom plugin for my WordPress site that relies on reading/writing from an xml data file within the plugin folder. When I test this standard PHP code for file reading/writing, it will let me create/write to files located at the wp-admin/ level, but not files within the plugin folder, although it can read from 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 debug error:

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

I'm currently running this off a local MAMP server, but want a solution that will let me package and publish the plugin on any WordPress server. What is the right approach?

Thanks-

like image 480
Yarin Avatar asked Jun 28 '11 11:06

Yarin


People also ask

How do I create a submission form in WordPress?

Within your WordPress dashboard, go to Forms > New Form and then give your new form a name. Once a new form is created, you'll be sent directly to the form builder where you can begin to build your form.

How do I upload a WordPress plugin to a file?

Go to Dashboard / Plugins / Add New and press “Upload Plugin” button on top of screen, as shown in the above image, in order to upload the file. Select the file from your computer and press “Install Now” button. When installation finishes, press “Activate” link to activate it.

How do I edit WordPress files?

Click into the theme directory of the template you're using. This is the theme you found earlier in the WordPress Appearance section. To open the File Manager editor, select the file you want to edit and click “Edit.” A new window will appear allowing you to select the editing method you wish to use.


1 Answers

Don't access it via HTTP if you want to write to the file. Access it directly instead for both reading and writing as it's much faster and the most direct method to access a file.

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

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

This will prevent you from making use of HTTP which should not be used at all because of performance reasons and because HTTP does not support writing. But foremost, as it's a file on the server you have access to, access it directly.

like image 64
hakre Avatar answered Oct 05 '22 19:10

hakre