PHP access to mail queue on Linux server - php

I wonder if someone can help with a query I have. My server recently had an email account hacked and subsequently a large amount of spam appear in the mail queue. I've changed the password on the email account in question and used qmHandle to remove the spam from the mail queue. I would like to prevent this from happening again and I was wondering if it would be possible for PHP to access the mail queue and run a cron job that could run every hour and run a script to alert me if the mail queue exceeds a set amount of mails so I could be alerted and react accordingly? My server is Linux running Redhat if that makes any difference?
Many thank in advance.

As i don't know which Maildaemon you use, i can just throw some things to think about:
To display the que, use "mailq" (on a Debian/Postfix system)
To access it from php, use "sudo" (execute a command as root from non priviledged user)
Maybe filter/group it by adding "grep" to "mailq"

Since you are using qmail, and you have qmHandle on the server, it's fairly straight-forward. qmHandle -s will give you some statistics, including the number of messages in the remote queue. The remote queue contains outgoing messages that are queued for delivery. You can cobble together a one-liner using grep and cut, which will give you just the count of the number of messages in the remote queue, like so: qmHandle -s | grep remote | cut -d: -f2

you don't need PHP to do that. A simple bash script ran by cron would do it. Somethig like that:
nbline=`mailq|wc -l`
if [ $nbline -gt $seuilMails ]
then
echo -e "\nSeuil queue postfix dépassé ($nbline lignes)" >> $msgFile
sendmail=true
else echo -e "\nQueue postfix normale" >> $msgFile
fi
if [ "$sendMail" == true ]; then
mailto_admins "$sujet" "$msgFile"
fi

Related

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

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!

PHP script to Check MYSQL Running or not?

I am looking for a PHP script which can check mysql is running or not in CENTOS / Linux VPS?
I have tried several method but its not working
First Method:
<?
$command = ('/etc/init.d/mysql restart');
if (! $dbh = mysql_connect('localhost','username','password') ){
$output = shell_exec($command);
echo "<pre>$output</pre>";
}
else
echo"nothing happened";
?>
Second Method:
<?php
// STOP + START = RESTART..
system('net stop "MySQL"'); /* STOP */
system('net start "MySQL"'); /* START */
?>
Both Methods dint not works for me in PHP..
Problem Is : these days my site having too much load of mysql, i tried several method but i am unable to stop its crashing.
therefore i decide to make a PHP script to check weather mysql is running or not?
If not then PHP script will perform Restart Mysql,
or else print "My Sql is running".
for this I've decided to set a Cron Job in PHP, that PHP script will monitor mysql is running or not.
I am also looking to save the logs in the end.. to check how many times mysql got restart.....
please someone find the fix of this issue.. and post here..
thanks in advance...
First of all, allowing MySQL to execute shell commands or executable programs is inviting a security disaster.
Secondly, if your site is hanging up because of too much load in MySQL, restarting MySQL from PHP is inviting a data loss disaster. Spend some time performance tuning your database. There is quite a bit of information about this on the internet.
You can configure your server (presuming you control the server and are not using virtual hosting) to allow read-only (!) access to the .pid file that is present while MySQL is running as suggested by #user1420752. You can check that it exists to see if MySQL is running. That does not ensure that it is at all responsive, though.
Alternatively, you can run just about the cheapest of all MySQL queries
SELECT 1
it will only run if MySQL is up, but does not require any IO to complete (see this).
There are quite a few monitoring solutions for operating systems (Windows/Linux) and your database. Some good ones are open source. I would suggest setting one up to notify you when CPU or IO utilization are high, or if the MySQL server stops, and focus your efforts on MySQL tuning.
You can achieve it by simple bash script. Schedule below script in cron on every 5 minutes or as per your requirement.
#!/bin/bash
EMAILID=yourmail#domain.com
date > /var/log/server_check.log
mysql -uroot -proot123 -e"SELECT USER FROM mysql.user LIMIT 1" >> /var/log/server_check.log 2>&1
if [ $? -eq 0 ]
then
echo -e "Hi,\\n\\nMy DB is running \\nThanks,\\nDatabase Admin" | mail -s "My DB is running" $EMAILID
exit
else
echo -e "Hi,\\n\\nMy DB is not running, so now starting it.\\nThanks,\\nDatabase Admin" | mail -s "My DB is not running" $EMAILID
service mysqld start
fi
Further this is just a check but not solution, you should check your queries in slowlogs or your db configuration to get root cause of it and work on it.
If your mysql service is block or stop running then, use following shell script to auto start your MySql service.
#!/bin/bash
now=$(date +"%T")
echo "in $(pgrep mysqld | wc -l) auto mysql start $now"
if [[ $(pgrep mysqld | wc -l) == 0 ]];
then
sudo -i | /etc/init.d/mysqld start
fi
Set Shell script in Cron job:
*/2 * * * * /bin/sh /home/auto_start_mysql.sh >> /home/cronlog.txt
For more detail check this URL: http://www.easycodingclub.com/check-mysql-running-or-not-using-shell-script-or-php-script/linux-centos/
Platform/version dependent, but how about:
$mysqlIsRunning = file_exists("/var/run/mariadb/mariadb.pid");

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!

Best way to ping client

Right, I have a PHP script at work where the server ping's a client. The problem I am facing is that sometimes the server cannot contact the client although when I manually ping the client it ping's successfully.
The ping command I am using is this ping -q -w 3 -c 1 < ipaddresshere >
What would be the best way of pinging the clients maybe 2/3 times leaving like a 2/3 second gap if a ping fails before a retry?
As you are in the unix environment, you can always make and then call a shell script to handle the looping and waiting. But I'm surprised that you can't do that inside of php.
Also, i'm not sure about your sample ping command, the 2 different environments I checked seem to have different meanings for the options you mention than what you seem to intend. Try man ping OR ping --help
The script below should give you a framework for implementing a ping-retry, but I can't spend a lot of time on it.
cat pingCheck.sh
#! /bin/bash -vx
IPaddr=$1
: ${maxPingTries:=3}
echo "maxPingTries=${maxPingTries}"
pingTries=0
while ${keepTryingToPing:-true} ; do
if ping -n 3 -r 1 ${IPaddr} ;then
keepTryingToPing=false
else
sleep ${sleepSecs:-3}
if (( ++pingTries >= maxPingTries )) ; then
printf "Execeeded count on ping attempts = ${maxPingTries}\n" 1>&2
keepTryingToPing=false
fi
fi
done
I hope this helps.
P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.
for php, you can try PEAR's Net_PING package.
here is a link guiding you through it
http://www.codediesel.com/php/ping-a-server-using-php/

Categories