Determining where fopen() is writing files when used from WordPress AJAX call [closed]

I have a WordPress Plugin which uses AJAX to send mail. It works fine. Now I want to put a bit of code to write a log file when the mail is sent.

The parameter $u is simply a bit of text to be logged.

function writeToLog( $u ) {
    $path="log.txt";
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (($h = fopen($path, "a")) !== FALSE) {
        $mystring = $u . ' ' . $agent . PHP_EOL;
        echo('mystring seems to be working');
        fwrite( $h, $mystring );
        fclose($h);
    }
    else
      die('WHAT IS GOING ON?');
}

It appears as though fopen() is working, but I can’t find the log.txt file. I thought it would be located in the same folder as the plugin. Where this log.txt file is being written? Do I need to provide an explicit $path to write this file within the plugin directory?

1 Answer
1

With your CODE as is, where the log.txt file will be written depends on PWD (Present Working Directory value). It can be your web root, or any where else.

However, since WordPress AJAX calls are made to wp-admin/admin-ajax.php file, PWD for AJAX is almost always the wp-admin/ directory. So if you use the file path as $path="log.txt";, the log file will almost always be created within the wp-admin/ directory.

Now, to make sure it’s created in your Plugin directory, you may use:

function writeToLog( $u ) {
    // this will create the log where the CODE of this function is
    // adjust it to write within the plugin directory
    $path = dirname(__FILE__) . '/log.txt';
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (($h = fopen($path, "a")) !== FALSE) {
        $mystring = $u . ' ' . $agent . PHP_EOL;
        echo('mystring seems to be working');
        fwrite( $h, $mystring );
        fclose($h);
    }
    else
        die('WHAT IS GOING ON?');
}

Since it’s WordPress (with default setup), you may use ABSPATH constant to write it in the Web Root as well:

$path = ABSPATH . 'log.txt';

BTW, it’s always better to write these sort of logs in your own plugin directory instead of web root. You better keep web root not writable by scripts (good for security).

Leave a Comment