PHP code not executing in cron job - php

I've a php script which will get all network card mac address and store first one in a text file.
Here is the code which I used to get MAC of system:
<?php
$mycom = shell_exec("ifconfig | grep HWaddr");
$findVal = "HWaddr";
$mac_arry = array();
while (strpos($mycom, $findVal) > 0) {
$start_pos = strpos($mycom, $findVal);
$mac=substr($mycom,($start_pos+7),17);
$mac_arry[] = $mac;
$mycom = substr($mycom, ($start_pos+10));
}
$fileHandle = fopen("/tmp/mac.txt", "a+");
fwrite($fileHandle, $mac_arry[0]);
fclose($fileHandle);
?>
If I execute this file directly in browser or through terminal, it works perfectly. But when I add this to cron for every minute, it doesn't work. Here is my cronjob:
* * * * * /usr/bin/php -f /var/www/html/test.php

by axiac
The cron job executes in an environment that is very different than the one you get in a terminal. The content of the $PATH variable is shorter and it's possible that /sbin (where ifconfig usually stays) is not included. That makes the shell_exec() call fail and the rest of the script doesn't matter. Use which ifconfig (in a terminal) to find out where ifconfig resides on your system and invoke it using its absolute path in shell_exec(). The same for grep (it probably can be found even without full path because it usually stays in /bin.)

Related

Cron job is not working-cpanel VPS Optimized 3

This is my code. File name is test_cron.php(inside the crtest folder).
Cron command is: /usr/local/bin/php -q /home/portroot/public_html/crtest/test_cron.php
It should be run on the server every minute. It should generate the text files every minute. But nothing is happen. I gave an email address also. But I didnt get any email. Please help me to correct this.
<?php
//Cron command: /usr/local/bin/php -q /home/portroot/public_html/crtest/test_cron.php
$filename = "./public_html/crtest".time().".txt";
$handle = fopen($filename,'w') or die("Cannot open file");
for($i=0;$i<10;$i++)
{
$con = "Hello world \n";
fwrite($handle,$con);
}
fclose($handle);
?>
u have to do 2 different test :
check ur script without using Cron by running it in browser and check if u get the result u want.
check ur Cron with a very sample script like an insert query to enter some data to ur database.
Then u can find the problem.
Please follow below step to check your code and setup cron on server:
1. First check your code is successfully running on your local system or not.
2. If you need to call a php script using URL; you can simply use lynx, curl or wget. Make sure you've placed your php script within the www or public_html directory and call the path properly on the cronjob.
*/2 * * * * wget -q http://localhost/test_cron.php
3. I've used this command to activate cron job for this.
/usr/bin/php -q /home/username/public_html/yourfilename.php
on mostly server and it works fine.
/usr/bin/php is php binary path (different in some systems ex: freebsd /usr/local/bin/php, linux: /usr/bin/php)

How can I make a cron to execute a php script?

I want execute a php script each five minutes at my server, it is a php script which works fine alone, I tried since my browser and since console using "php -f php_file.php". But I need execute it automatically every days. I was searching on Google and here to make it but any solution worked for me:
First I edit my crontab and I also restart the cron to make sure that it was updated correctly.
*/5 * * * * /usr/bin/php /var/www/myscript.php
and I tried the following too:
*/5 * * * * /usr/bin/php -f /var/www/myscript.php
I made the script executable too, review my system log (where I can see that my cron is executing correctly, but it doesn't execute php script) and I also try to redirect the output of cron to a file, but it leaves the file empty.
Anyone can help me?
Best regards
You were on the right track by making your script executable.
Do it again if needed
$ chmod +x script.php
Add this to the very top of the file:
#!/usr/bin/php
<?php
// here goes your script
you can test if the script executes by running it like this
$ ./script.php
set-up your cron job like below to set-up some logging but make sure you output something from your script, use print or echo and a relevant message.
*/5 * * * * /var/www/script.php >> /var/www/script.log 2>&1
we are redirecting both standard output and errors into the script.log file.
check every 5 min for activity.
Update:
Try this in your php script
$file = '/var/www/script.txt';
for($i=0;$i<9;$i++){
$entry = date("Y-m-d H:i:s") . " " . $i . PHP_EOL;
echo $entry; // this should write to the log file
file_put_contents($file, $entry, FILE_APPEND | LOCK_EX);
// and this should write to the script.txt file
}
basically we are giving the full path to the file and passing the FILE_APPEND flag so we don't overwrite every time.
Run the script and check if the file is created, the default behavior is to create the file if it doesn't exist.

Not able to run php script from cron

I am running LAMP system on ubuntu 14.04. I have an rss feed using php which runs every 1 hour and MySQL stores data. My php file used to run perfectly using php in cron some 15 days but its not working anymore
My cron is as below
0 * * * * /usr/bin/php /var/www/html/rss.php >/dev/null
My php script is working perfectly from browser(firefox/chrome)
When I run the php script using wget in cron it works fine
0 * * * * wget http://www.mywebsite.com/rss.php >/dev/null
Your script is using relatives pathes.
When you open this script in a browser it tries to find files in /var/www/html/.
When you do it in the cron it tries to find files in /.
Put this in the beginning of your script:
define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
Now change every relative include or opener:
include ROOT . "db.php"
...
if (($handle = fopen(ROOT . "tbcatlist.csv", "r")) !== FALSE)

set cron job from php

I try To set cron job from php but every time i try the code blow it's not work.
tell me what is the problem with this code
$cron = $this->generator();
file_put_contents("cron.txt", $cron);
shell_exec('crontab cron.txt');
generator function make cron job string like below
12 1 * * * /usr/bin/sample >/dev/null 2>&1
the cron.txt file is fine. it contain the string but shell_exec some how not working
Running your scrip with the hardcoded $corn locally works fine for me, i've included a couple of lines to clear the crontab in the beginning and couple of line to confirm the entry. see bellow.
$cron = '12 1 * * * /usr/bin/sample >/dev/null 2>&1';
file_put_contents('cron.txt', $cron);
shell_exec('crontab -r');
shell_exec('crontab cron.txt');
// To check the result
$output = [];
exec('crontab -l',$output);
print_r($output);
Output:
Array
(
[0] => 12 1 * * * /usr/bin/sample >/dev/null 2>&1
)
And here is a way to check the result of the crontab cron.txt execution:
$output = $return = [];
exec('crontab cron.txt',$output, $return);
var_dump($output, $return);
There will be no output nor return in case of success:
array(0) {
}
int(0)
after many search in Dr Google i found out the answer
i have to change the use to Apache user which is www-data
so the command change to crontab -u www-data cron.txt
The issue is that the apache server will run as a separate limited resource account that rightfully should not create cron jobs. This is a pretty easy way to get the host server compromised. Especially if this is running in a publicly accessible ip address space.
However, if the environment is secure and your server administrator allows, you can have the apache process either run as a higher privileged account (yours for example) or to use the suexec feature to run as a designated account with limited but appropriate permissions.

How to run crontab-e?

I am currently reading this documentation here where I want to use CRON. Now it says in the first section that I need to enter in a command: crontab -e.
Do I only need to enter this in a simple text editor file and just upload the file into the server?
I am using helios.hud.ac.uk so would this be the correct command:
* * 25 10 * helios.hud.ac.uk/u00000000/Mobile/inactivatesession.php
This will execute this php script below (inactivatesession.php):
<?php
include('connect.php');
$createDate = mktime(0,0,0,10,25,date("Y"));
$selectedDate = date('d-m-Y', ($createDate));
$sql = "UPDATE Session SET Active = ? WHERE DATE_FORMAT(SessionDate,'%Y-%m-%d' ) <= ?";
$update = $mysqli->prepare($sql);
$update->bind_param("is", 0, $selectedDate);
$update->execute();
?>
The url for this php script is: helios.hud.ac.uk/u00000000/Mobile/inactivatesession.php
I havn't used CRON before so just need little help on it.
Thanks
If you are making a crontab that will access a remote webpage (which is what this is as it is not on your local server) you need to prepend the URL with wget
* * 25 10 * wget -O - http://helios.hud.ac.uk/u00000000/Mobile/inactivatesession.php
It will run the script on the server and output it to standard output (which in most servers will be emailed to you)
This assumes that you have a linux machine. crontab -e sets up a cron tab for your user account. So you can't really upload a crontab, but if you have cpanel or similar, most times you have access to cron from there.
You open a shell (probably through SSH) to your server
You run the command crontab -e
You edit the crontab according to your needs (if you want to run a php script over http you need to use wget)
You save and exit If you didn't make any mistakes, you will get a message that crontab was updated

Categories