Nick
Nick

Reputation: 936

PHP cron job not running log via file_put_contents()

I am running a cron job every minute which runs a loop; I am outputting the results from each loop into a log file. This function is inside a class, and runs absolutely fine when the function is called manually. However, when the function is called via a cron job, file_put_contents() does nothing (the rest of this function works fine i.e. the table insertion).

protected function updatePair( $time, $pair_reference, $price, $exchange_id ) {

    $exchange_reference = get_field('reference', $exchange_id);

    global $wpdb;
    $table = $wpdb->prefix . $pair_reference . '_' . $exchange_reference;

    // Insert time and price into table
    $wpdb->insert($table, array(
        "time"  => $time,
        "price" => $price
    ));

    //Write action to txt log
    $log  = "Pair: ".$pair_reference.' - '.date("F j, Y, g:i a").PHP_EOL.
            "Attempt: Finished".PHP_EOL.
            "-------------------------".PHP_EOL;
    //-
    file_put_contents('log/exchange.txt', $log, FILE_APPEND);

}

Upvotes: 3

Views: 1756

Answers (2)

J'aime Java
J'aime Java

Reputation: 46

Just in case someone face the same problem in the future, the problem was with the permissions, to solve the problem you need to change the permission of the php script file, it must have the write permission), to do that:

  1. Using FTP Client (i.e. Filezilla): right click on the script file, and choose File permission, give write permission to the user and group of users (i.e. 766)

  2. Using Terminal:

    chmod 766 /path/to/php_script

Upvotes: 3

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

First make sure log folder is exist or you can check by below code:

if(!file_exists(__DIR__ . '/log') && !is_dir(__DIR__ . '/log')){
    mkdir(__DIR__ . '/log');
}

Second use absolute path:

file_put_contents(__DIR__ . '/log/exchange.txt', $log, FILE_APPEND);

Upvotes: 2

Related Questions