简体   繁体   中英

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 ie 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);

}

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 (ie Filezilla) : right click on the script file, and choose File permission, give write permission to the user and group of users (ie 766)

  2. Using Terminal :

    chmod 766 /path/to/php_script

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM