Ahmad
Ahmad

Reputation: 12737

echo() and file_put_contents() not working when triggered by crontab job

I have setup a crontab job to run every hour.

m | h | d | M | w | command
--|---|---|---|---|----------
0 | * | * | * | * | php path/job.php

Inside job.php I have this code:

<?php
    $today = date('Y-m-d');
    echo   "echo: Today is $today <br>";
    printf("printf: Today is $today \n");

    file_put_contents("/path/$today.log","log file created");
    exit();

When I visit job.php on my browser, I see the expected output:

echo: Today is 20-08-2018
printf: Today is 20-08-2018

And a new file 20-08-2018.log is created.

However, when the crontab runs this job.php, I get an email notification of the output generated by the job, and it only contains:

printf: Today is 20-08-2018

Moreover, I check if the file is generated/appended, but fail to find any evidence of the file getting generated (even if I delete all log files before waiting for the crontab to run the job).

How can this be explained? What can I do to make file_put_contents work when a crontab job is automatically triggered?

Edit: I forgot to mention that I have checked for php_errorlog suspecting something went wrong when crontab triggers the job, but failed to find any error.

Upvotes: 0

Views: 1139

Answers (2)

LahiruTM
LahiruTM

Reputation: 648

Try This

$today = date('Y-m-d');
$myfile = fopen("/path/$today.log", "a") or die("Unable to open file!");
$txt = "Today is $today <br> \n";
echo   "echo: Today is $today <br> \n";
fwrite($myfile, $txt);
fclose($myfile);
exit();

Upvotes: 0

Manjunath Muniraju
Manjunath Muniraju

Reputation: 44

@Ahmad: Try this Solution

Try adding full path in file_put_contents() function and giving appropriate folder permission.

ex: file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . "{$today}.log", "log file created")

Upvotes: 2

Related Questions