2

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?

3
  • 1
    in the /wp-admin, probably, if the code is executed over admin or the root dir. You should provide full path like this $path = plugin_dir_path(__FILE__) . 'log.txt'
    – Ismail
    Feb 7, 2017 at 20:31
  • Perfect. It was, indeed, in the /wp-admin. If I want to write to the root folder of the site, is there a built-in function for that?
    – jchwebdev
    Feb 7, 2017 at 20:40
  • $path = ABSPATH . 'log.txt'
    – Ismail
    Feb 7, 2017 at 20:42

1 Answer 1

3

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).

2
  • Is there a preference between ABSPATH and get_home_path()?
    – jchwebdev
    Feb 7, 2017 at 21:06
  • ABSPATH will give you web root, on the other hand, the result of get_home_path() can be different based on the home option setting in WP Admin.
    – Fayaz
    Oct 21, 2021 at 15:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.