crontab command - execute and than email log file (with 2 options) - php

I need to run my php code each hour, and my knowledge about crontab/cronjob is pretty bad.
I want the script to run each hour and send email for 2 case: success and failure.
I wrote this code but I don't know if it's good for crontab (I think it's not working):
0 * * * * php <full-path-script>
if [ “$?” = “0” ]; then
echo “Backup Process was Successful. A new log file <filename>.txt has been
created” | mail -s “Backup Status Successful” <email> -A <path>
<filename>.txt
else
echo “Backup Process Failed. Please contact System Administrator. A new log
file <filename>.txt has been created” | mail -s “Backup Status Failed”
<email> -A <path><filename>.txt
if you think I should do it different please explain and show me how.
BTW - I'm working with postfix.

OK, You can solve your issue with writing / running two PHP scripts together.
Existing script, just add writing to file, write it in CSV format the start time and the end time of the script. [ Each run in new line ]
Run another "deamon" PHP script every x minutes via crontab that parse the CSV file, the script goals are: Parsing the CSV file and searching for lines with start time and without end time, and sending an email if something wrong in CSV file.
Pay attention,last line in CSV file can be active process, so take interval or time time that you think its should done.
//Create another PHP file / class that sends an email and control it from the php code.
// the message
$msg = "First line of text\nSecond line of text";
// send email
mail("someone#example.com","My subject",$msg);
What can interrupt in PHP in your code ? use timeouts / try catch / reties mechanism to reduce the failures.

OK, here is what I've done to solve my problem:
First - Be sure to write all your shell scripts on Linux (otherwise you script will get messed up and you won't even be able to see it), you can setup your own Linux using vmware or other program.
This is my shell script:
`#!/bin/bash
/usr/bin/php <full-path-script>
if [ “$?” = “0” ]
then
echo “Backup Process was Successful. A new log file `date "+\%Y-\%m-\%d-
\%H"`.txt has been created” | mail -s “Backup Status Successful” <email-
address> -a <path>`date "+\%Y-\%m-\%d-\%H"`.txt
else
echo “Backup Process Failed. Please contact System Administrator” | mail -s
“Backup Status Failed” <email-address> -a <path>`date "+\%Y-\%m-\%d-\%H"`.txt
fi`
In order to make sure your script will send error into $? you should avoid using die(); on errors, In fact you should use exit(1); (it'll put 1 in $? so we'll know the script failed to run).
Don't forget to make cronjob that will task this script for you and send you notifications to your email address :)
I hope this help anyone!

Related

cron in windows 10 permission and xampp setup

I am trying to send email using PHP mailer at regular interval. I am using windows 10 and have set up a cron . Here is .bat file code .
#echo off
schtasks /Create /TN XAMPP /TR "C:/xampp/php/php-win.exe C:/xampp/htdocs/aurr/emailcron.php" /SC MINUTE /MO 1
pause
Problem is even though I am able to send emails ,there is no attachment in received emails .But when i manually execute emailcron.php ,I get attachment in received email.My guess is this might be because of permission issue .How do I fix this error?
When the script is run by the cron task it's run by whichever user the cron script is run as (a default if you don't override it), and when you run it yourself it's obviously run as you. If you have permission to read the file but the cron user does not, it won't be able to send the file.
Several things to look at here:
Run the cron task as a user that does have permission to read the
files, e.g. you.
Give the cron user permission to read the files.
Make your script check for a successful return value when it adds
attachments.
For the last of these, do it like this:
if (!$mail->addAttachment('path\to\file')) {
echo "Could not access path\to\file";
exit;
}
That way it will generate an error and not send the message if it can't access the file, rather than failing silently as it's doing at present.

How can i know if a command exection is completed and notify in case of an error or not?

I am running a command that creates a zip file in my php controller script.
Once the file is created, an email is been send to a user for notification. The command is as follows :
system("7za a path/zip_file -mem=AES256 -v2g -mx9 -pPassword path/zipcontent > /dev/null 2>&1 &");
The creation of the zip file last for about 20 minutes and I wish to send the email once the file is created completely (that is after the 20 minutes) or if an error occur notify the user of the error.
How can I do to know if the execution of the command is completed and file well created before sending the mail in case of an error or not?
Thanks in advance.
A simple trick is to write error to a file like command1 2> myerror.txt and then use a cron job to send this file every 20 minutes by mail, and remove it. in case of no error, there is no file to send. so basically you just need a cronjob and a simple if-condition script.
An other method is using journalctl utility to send errors to specific output.
You even can use sed and grep to redirect error level to a file, then email it (or send to wall)
For notification, you can use yourProgram & notifyScript. if the first command has completed successfully, the second command will run.
With "&" at the end of command, you run in background that command (background on OS, non php), then system() php function return output immediately also if command work for 20minutes. Php script goes to the next instruction until has terminated without wait end of execution command run with system().
If you want to check when command are terminated, you can add a command in your system() call for a check.
7za has many exit code (see https://sevenzip.osdn.jp/chm/cmdline/exit_codes.htm)
system("7za a path/zip_file -mem=AES256 -v2g -mx9 -pPassword path/zipcontent > /dev/null 2>&1 ; echo $? > /tmp/myfile.txt &")
With this you can try to write exit return code (in shell command "$?" is exit return code of previous command) to a tempfile and check it periodically. If it contain 0, extract has successfull then you can send an email.
Alternatively, you can write a bash script shell that does extract, check, send email and call this script trought system() function
It's not a best solution for me, but explain how work with external process in php using system()
There is a PHP extension , https://www.php.net/manual/en/book.pcntl.php, maybe it can help you

Way to Disable Cron log files BUT still send script output by email?

Right now my cron job is running but it creates a new log file every time it runs, which is both ridiculous and unnecessary. What I want is a NO log file at all (I will never check them, and I don't want to have to go in and clean them up). If I set it to send an email it just sends an email saying it ran ok and the output of the script is contained in the log file.
BUT - I need to see the output of the PHP script it's executing as it contains success / fail information and in the future probably a list. If I have to I can just make the PHP script send an email instead of the CRON job, but can CRON send an email with the output of the script, yet create no log file?
With this command I've disabled emails but it still creates a new log file with the script output every time it runs:
wget *webaddress*/generate_late_fees.php >/dev/null 2>&1
In shared hosting you usually don't have any control over the syslog and cron daemon anyways, so there's no chance to turn off logging for that cronjob.
Just do the email stuff from within the script and don't rely on the crond's automatic output to email forwarding.
Another option is to do the email stuff from the console using the mail command. Just pipe wget's output to the mail command.
wget *webaddress*/generate_late_fees.php | mail -s "this is the subject" "to#address" >/dev/null 2>&1

sending email periodically through php script

I am working on an automatic monitoring system. I have made a .NET application which have MySQL database. For this I developed a normal ADMIN Panel where admin can log in and get necessary reports coming from various queries fired on the database. There is also a "summary Report" in the panel which is just the rough weekly summary. Now What I want is, I want this report (all text) to get sent automatically to some email "xxxxx#xxx.com" with a seven day period. I have used some PHP scripts previously to send email on submit button click. Like the one below.
<?php
if(isset($_POST['isPost']))
{
$header="From:".$_POST['customer_mail']."\r\nName:".$_POST['name']."\r\nCity:".$_PO ST['city'];
$subject = $_POST['title'];
$message="From:$_POST[customer_mail]\r\nName:$_POST[name]\r\nPhone:$_POST[city]\r\n \r\n\r\n\r\n".$_POST['details'];
$to = 'xxxxxxxxx#xxx.com';
$send_contact=mail($to,$subject,$message,$header);
if($send_contact)
{
echo "<h6 style='text-align:center;color:green'>Sent Successfully</h6>";
}
else
{
echo "<h6 style='color:red'>Error sending e-mail'</h6>";
}
}
?>
this is normal mail sending script which works fine. But for the above purpose I want, Can anyone help me to set this action periodically and automatically or point me in the right direction on how to do this. I have googled for such php script but no satisfied results.
~ Regards
You can do this with cronjobs.
A long running process which executes commands at given times / dates / intervals.
Depending on what system you are, there are different methods.
If you have the script on a webserver someone is running for you / Webhost service
Ask the system administrator to run the script with a cronjob. Or search for any help documentation if you can setup this yourself in any admin-panel. Ask your webhoster /system admin for more information.
If you have the script on your own local machine:
UNIX
Try reading about crontab on how to run the php script, or any script for that matter.
For example type crontab -e and add the line below in your crontab, the cronjob will run your script every hour:
00 * * * * /usr/local/bin/php /home/Low-pointer/myscript.php
Here is some more information if you want to play with the intervals
Windows
If you use Windows you can use scheduled tasks to run the php command.
For example add the following command to the scheduler: C:\wamp\bin\php\php.exe -f C:\wamp\www\my_script.php
You can also use web cron services (Google it) these are online services which run a page (for example on your webserver) on designated times. For free or paid.
You can use Cpanel to send schedule emails through the cronjob(if you are using it).
Once you open cpanel theere would be crontab system.
Add your current code to a file(xx.php) and add this command to crontab in cpanel ,
/usr/bin/php -q /home/public_html/xx.php
like everyone have already said you must use cronjob to make your task.
I assume you use a Linux OS as your production environment.
So you need:
1) A php endpoint ( eg. www.mywebsite.com/emailsend.php ) OR a CLI php script that when called send the email.
2) The correct crontab rule
Here below an example of a simple shell script ( mailsend.sh ) that call an endpoint using CURL and save an html file with an eventual response given by the webserver
#!/bin/bash
curl http://www.mywebsite.com/emailsend.php -o /path/to/my/mailsendreport/"$(date '+%Y-%m-%d-%H-%M-%S')".html
To add a scheduled task to cron
crontab -e
then add a rule like below
50 23 * * 6 sh /path/to/mailsend.sh
What "50 23 * * 6" means? It means that every sixth day of the week, in the 23th hour, in the minute 50 your sh script will be called, and then your web app and the email is sent.
Once I wrote a small doc about this you can see it here
Cheers
You're looking for "cron job".
Edit: Or since it sounds like you might be on Windows, "Scheduled Tasks"

Get name of running process in php

I've been searching and can't find something clear, at least for me
I've made a newsletter and sent it with a mail script
Since it had a lot of emails, I said ignore_user-abort and let it work sending emails even if I closed the browser
Now I'd like to check the progress, I mean, if it has finished all the emails
I understand that there are functions like posix_kill and getpid but I don't know if they are the right ones to use
getpid gives me the id but how can I know the name of the script running? Maybe another script is running that I don't know
thanks a lot
Try the following:
Before the script start to send emails create a file by example emails.log
And when the script is done, remove it,
When the script starts again ask if exists, and if exists kill the script,
The only issue i see can happen is if the script dies unexpected or the page give a timeout the file will be not removed
For avoid this you can create a cronjob in your server and configure for run it daily, weekly or whatever you want, the shell script will look something like:
newsletter.sh
#!/bin/bash
if [ ! -f /tmp/newsletter.log ]
then
touch /tmp/newsletter.log
php /var/www/newsletter.php >> /dev/null
rm /tmp/newsletter.log
fi
Good luck!

Categories