Search code examples
phpfilefwrite

How does PHP interpret local paths and where does it open files?


I'm trying to figure out how a WordPress theme works. For this, I want to write to a file from various functions. The file is at the root of the site.

fwrite(fopen("output.txt", "a"), "Test output\n");

From /test.php, this outputs to /output.txt. I'd like to write the value of a variable in a deeply-nested function. Copy/pasting the above code outputs to somewhere I can't find. This:

fwrite(fopen("/output.txt", "a"), "Test output\n");

doesn't work, either. It raises:

Warning: fopen(/output.txt) [function.fopen]: failed to open stream: Permission denied in /public_html/test.php on line 17

Warning: fwrite() expects parameter 1 to be resource, boolean given in /public_html/test.php on line 17

The manual specifies some stuff about schemes and wrappers, but doesn't say very much about paths.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode, or open_basedir, further restrictions may apply.

How do I properly reference the path I want, and how does PHP choose where to write with a relative path?


Solution

  • If you are not using absolute paths, the path is relative to the index.php of wordpress. To access a file that is stored in the same folder as your php file use the global constant __DIR__:

    fwrite(fopen(__DIR__ ."/output.txt", "a"), "Test output\n");
    

    __DIR__ will give you the absolute path to the current php script.