I understand SO is for questions but no matter how many tutorials I have looked up, I cannot get my crontab to work and I am building an website that will rely on crontab to reset a particular setting in my database every night.
Here is my crontab file:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
* * * * * /usr/bin/php -q /var/www/html/cron/index.php
If I try to cd to /usr/bin/php i get
-bash: cd: /usr/bin/php: Not a directory
So I cd'd to just /usr/bin/ and this is what i found:
-rwxr-xr-x 1 root root 27216 Feb 10 15:08 pgrep*
lrwxrwxrwx 1 root root 21 Jun 13 09:36 php -> /etc/alternatives/php*
-rwxr-xr-x 1 root root 9049256 Jul 2 11:57 php5*
If I cd to /etc/alternatives I find:
lrwxrwxrwx 1 root root 13 Jun 13 09:36 php -> /usr/bin/php5*
I go back to the bin file, php5 has the * symbol and is green.
-rwxr-xr-x 1 root root 9049256 Jul 2 11:57 php5*
My PHP script. Very simple. Checks for a cookie and if it exists increments it by one. I then check the results on another page. Manually this works. With crontab, cannot get it to work.
if (!empty($_COOKIE['cronTest'])) {
$int = $_COOKIE['cronTest'];
$int++;
setcookie("cronTest", $int, time()+3600);
}
Most likely, your script inside /var/www/html/cron is owned by www-data user. Depending on your setup the user executing the cronjob doesn't have permissions to run this file.
There are no $_COOKIEs on the command line. A cookie is sent by the users browser. As cli isnt a browser, so you can't read the cookies value. Though you could access a users $_SESSION, but that's another story. Have a look here Is it possible to read cookie/session value while executing PHP5 script through command prompt? for further details.
Your cronjob line looks valid, so the problem will be one of above points. To verify the first, try something without the use of $_COOKIE in your file, like simply
mkdir('/var/www/html/cron/testdir');
just to see if the file can be accessed and a directory is created inside above dir. If it can't be accessed, create a new group and add both the current user ( find out with
ls -al
in /var/www/html/cron ) and the user running the cronjob to the group, then make that group own the file you want to run. See the accepted answer on this question: Set user permissions | Artisan command will not run in code but works fine on command line I posted some time back on how to do that.
For the $_COOKIE problem, you will have to find another solution. For example use Redis or Memcached as a caching service that can be accessed both by online and cli configurations.
Consider to add
1>> /dev/null 2>&1
to the end of your cronjob line, if you don't do so and let cron run this every minute, you will get masses of logfiles.
For the sake of completenes on possible pitfalls when working with php and the cli, allways make sure to provide full paths to your files.
Related
I have the following set as a cron job:
*/1 * * * * /usr/bin/php /var/www/html/recalls/php/savesjson.php
I checked the status and I get this back.
Mar 10 16:29:01 big-hoster CRON[30417]: (root) CMD (/usr/bin/php /var/www/html/recalls/php/savesjson.php)
Mar 10 16:29:02 big-hoster CRON[30416]: pam_unix(cron:session): session closed for user root
The savesjson.php file should execute and basically save a new JSON file (current.json) in the same directory. If I just run this file (by going to the URL), it works perfectly. However, my cron isn't actually updating the current.json file.
current.json has permissions as follows:
-rwxr--r-- 1 root root 0 Mar 10 16:17 /var/www/html/recalls/php/current.json
savesjson.php has permissions as follows:
-rwxr-xr-x 1 www-data www-data 213 Mar 8 14:11 /var/www/html/recalls/php/savesjson.php
What am I missing here?
UPDATE: If I try to execute from the CLI, like so:
# /usr/bin/php /var/www/html/recalls/php/savesjson.php
It appears to execute, but the script doesn't do what it's supposed to (create new file) and there are no errors in my PHP logs. However, the PHP does work if I go directly to the URL (example.com/php/savesjson.php).
after a week of trying i dont know what else to do.
I have a simple php script that is on my webserver called getpoem.php
The script opens up a website pulls its content and saves it to a poem.txt on the server
<?php
//File to extract the Poem of the day
$homepage = file_get_contents('http://SomeWebsite.com/today.php');
$poemALL = substr($homepage,strpos($homepage,"<p>"),strlen($homepage));
.
. // extracting the poem and saving it to $poemFinish
.
file_put_contents("poem.txt", $poemFinish); ?>
so this is a fairly simple script (it works fine if i manually execute it). This script should be executed with the www-data user with its cron so i opend up cron with this command and entered the command it should run
sudo crontab -u www-data -e
0 3 * * * php /var/www/html/getpoem.php
to avoid any permission problems i gave the getpoem.php and poem.txt rwx rights like this (i know i should change it when its live but this is just to test)
-rwxrwxrwx 1 www-data www-data 1189 Aug 17 15:07 getpoem.php
-rwxrwxrwx 1 www-data www-data 1335 Aug 17 15:07 poem.txt
So this is the setup, but it will not execute.
What i did so far changing the "php" to /usr/bin/php to secure that cron know what php is.
Next thing i did was making shure that cron was running so i changed the cronjob to
2 * * * */usr/bin/php /var/www/html/getpoem.php | > /var/www/html/test.txt
wich again did nothing .... so i changed it to
2 * * * */usr/bin/php /var/www/html/getpoem.php | > /tmp/test.txt
that did not run the php file but created a empty (-.-") file called test.txt in my tmp dir.
So i think the problem must be someware in the acces rights of my www-data user. It's just very wierd because all my webcontent (php files, webapp usw.) are also owned by the www-data user and they run smoothly.
Do i need to grand extra privileges for the cron of www-data ?
When running php from cron, your working directory usually isn't the directory the file is located in. When writing a file, it might try to write the file poem.txt relative to / which usually isn't writable.
So you either set the working directory or you should use "absolute" paths. So for example:
file_put_contents(__DIR__.'/poem.txt');
where __DIR__ is a magic constant that contains the directory where the current file is in.
I have developed an agenda which works (server-side) with PHP and MySQL. The last thing I need to do is to make an authomatic daily backup of the database.
This is what I have thought may be the easiest: Write a php script which once every 24hs saves a file(Whose name would be a timestamp) in certain folder in the server. Combining this with time machine or some other backup software to backup this folder into an external disk should be enough.
So now, the questions are: How do I make a php script to run automatically once per day? How do I save a file with sql backup from a php script?(Similar to phpMyAdmin export as sql)
Thanks!
If you are running apache server:
sudo nano /etc/crontab
Add below line:
0 0 * * * root mysqldump -u root -proot db_name > /home/username/db_backup/$( date +"\%Y_\%m_\%d" ).sql
0 0 * * * => every 24 hours
If your server is a linux, you can make a cron using this script : cronsql.sh .
#!/bin/bash
path=/home/backup/
projet=(databasename1 databasename2)
now=$(date +"%Y-%m-%d")
for arg in ${projet[*]}
do
if [ ! -d $path$arg ]; then
mkdir $path$arg
fi
cd $path$arg
mkdir dump$now
cd dump$now
mysqldump -dBR --triggers -p"dbpassword" $arg > structure.sql
mysqldump --no-create-info -p"dbpassword" $arg > data.sql
done
It ll generate a folder with database name.
Inside, a folder with date
Inside the folder, a structure.sql file and a data.sql file
>databasename1
---->20151009
---->data.sql
---->structure.sql
---->20151008
---->data.sql
---->structure.sql
---->20151007
---->data.sql
---->structure.sql
for the cron
use crontab -e
then add 59 23 * * * /home/backup/cronsql.sh if cronsql.sh is in /home/backup/
And last but not least,
you can add in crontab
01 01 * * * find /home/backup/ -mindepth 2 -ctime +30 -exec rm -fr {} +
It ll delete every file / folder older than 30 days.
So you have a backup for every last 30days.
And no need to clean it manually
I found out, that you can do it with a *bat, if you are running windows.
This will safe your databases as zip, you also can upload them into ftp by changing this script a little bit.
Follow this link:
http://www.redolive.com/utah-web-designers-blog/automated-mysql-backup-for-windows/
It's easy to do, if you have any questions just ask
I want to edit the crontab of root from the web interface. I have Apache and PHP installed on my Ubuntu. If there is any permissions required please also mention that.
I want to edit the crontab of root. I have some jobs running in that crontab. One of my projects wants me to change the running jobs Time from web interface.
So please tell me how can I access the crontab of root and edit it.
permission problems: solve those by allowing www-data to run the appropriate commands via sudo.
run crontab -u root -l to get the current crontab, edit it with php string manipulation code of your liking and intall it with crontab -u root $FILE. i recommend to place markers in the file to make it easier to find the correct places to edit like so:
# Edit this file to introduce tasks to be run by cron.
# ...
# m h dom mon dow command
0 14 27 * * backupmails-monthly.sh
0 14 * * 5 backupmails-weekly.sh
# MARKER_EDIT_HERE_START
0 14 27 * * job_to_edit.sh
# MARKER_EDIT_HERE_END
a better solution if jobs run regularly: don't put them in the crontab but in /etc/cron/cron.{hourly,daily}.
if you have access to the console, you should install webmin for web management interface of the server
http://www.webmin.com/
These days there are tools like
chronos (depends on apache, has a dockerfile)
luigi from spotify
minicron
More options found at the github topic: cron
I'm using the ls command via PHP and exec() and I get a different output than when I run the same command via the shell. When running ls through PHP the year and month of the date get changed into the month name:
Running the command through the shell:
$ ls -lh /path/to/file
-rw-r--r-- 1 sysadmin sysadmin 36M 2011-05-18 13:25 file
Running the command via PHP:
<?php
exec("ls -lh /path/to/file", $output);
print_r($output);
/*
Array
(
[0] => -rw-r--r-- 1 sysadmin sysadmin 36M May 18 13:25 file
)
*/
Please note that:
-the issue doesn't occur when I run the PHP script via the cli (it only occurs when run through apache)
-I checked the source code of the page to make sure that what I was seeing was what I was getting (and I do get the month name instead of the proper date)
-I also run the ls command through the shell as the www-data user to see if ls was giving different output depending on the user (the output is the always the same from the shell, that is I get the date in yyyy-mm-dd instead of the month name)
Update with answer
alias was giving me this:
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
From those aliases I was unable to find a switch that was directly responsible for the time display:
-C list entries by columns
-F append indicator (one of */=>#|) to entries
-A do not list implied . and ..
-a do not ignore entries starting with .
-l use a long listing format
However using --time-style=long-iso in PHP did fix the issue.
ls has a couple command line options for date display format. check that your command line version isn't aliased to include something like ls --time-style=locale. The PHP exec'd version will most likely not have this aliasing present and is using default ls settings.
ls output depends from current locale settings. When you run it from console on behalf yourself it uses your locale settings, but user www-data has own locale settings (which probably differ from your). So, I suggest to you specify locale settings explicitly:
exec("LC_TIME=POSIX ls -lh /", $output);
where instead of POSIX you may substitute locale which you want to use.