Home > Software design >  Wordpress can't write file
Wordpress can't write file

Time:05-05

I'm working on a Wordpress plugin and running into this problem. My plugin can't write files onto disk. Here's my test code.

<?php                                                                                                  
    $fl = fopen ( "output/test.txt" , "w" );
    fwrite ( $fl , "This is a test" );
    fclose ( $fl );
?>

If I run that in a standalone PHP file then test.txt appears as expected and "This is a test" is in the file.

If I run that as part of a Wordpress plugin nothing happens. No errors are generated and nothing ever appears in the folder.

All of the scripts and the folder are owned by the apache user (www-data), folder permissions are 775. I also tried 777 but that didn't change anything so I put it back.

What should I try next or what other information can I provide?

CodePudding user response:

You need to be using your absolute path or DOCUMENT path .. What you have right now, is trying to look for a directory called output in the root of the filesystem or root of the application where the actual call is made, so if you're inside a class directory when the call is made, it's going to be looking in THAT directory instead of the one the script is in.

<?php                                                                                                  
    $fl = fopen ( "/var/www/path/to/your/wp/output/test.txt" , "w" );
    fwrite ( $fl , "This is a test" );
    fclose ( $fl );
?>

OR

<?php                                                                                                  
    $fl = fopen ( $_SERVER["DOCUMENT_ROOT"] . "/myWPFolder/output/test.txt" , "w" );
    fwrite ( $fl , "This is a test" );
    fclose ( $fl );
?>
  • Related