call php function every 10mins for 1hour - php

got this code that should check if url is available and also give me ping:
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
How do i make it so this function would be called every lets say 10minues for 1hour (6times in total) ?

I would recommend you to make use of cron jobs if you are using a Unix server or Windows Task Scheduler in the case of windows.
Like this you will be able to use programmed tasks.
In the case of using cron you could do it easily like this:
*/10 * * * * php -f your_relative_or_full_path_URL/params > /dev/null

depends: do you want to do that just once?
Then you can call the function inside a loop and use sleep() after each execution of the loop.
Do you want to do it everyday? or one specific day each week/month? use a cron.

Use a simple for-loop and the sleep command:
for ($i = 0; $i < 6; $i++) { // Run the code 6 times
test($url);
sleep(10 * 60); // Sleep 10 Minutes
}

Send Email every day in a Month. I used it in daily backup mail..
<?php
ignore_user_abort(true); //if page is closed its make it live
for($i=0;$i<=30;$i++)
{
$to = "someone#exmple.com";
$subject = "Test mail $i";
$message = "Hello! This is a simple email message.";
$from = "from#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
sleep(24*60);//send mail in every 24 hour.
}
?>

Related

Foreach function gives 503 Service Unavailable

It is 1 AM and I am struggling for 3-4 hours to see what's wrong with my script...
My database has ~400 emails. I set $ChunkSize as counter for the loop and also to count which is the next chunk to be processed.
I've set some echo() to debug
echo "This is the " . $GLOBALS["ChunkSize"] . " chunk. <br>";
It should output what chunk is processed at that time.
If I disable mail() then I don't get 503 Service Unavailable but every echo() displays at the same time, not in the order of processing.
I also found out that some emails arrive, but not to everyone. Also, if some emails are sent, that means foreach() should have processed at least one chunk, that means it should display at least one echo().
I've set break 1; so every time it breaks out of foreach() it should display the echo() with the chunk number processed by foreach() but it doesn't.
What I am doing wrong?
$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($dbname, $connection);
$result = mysql_query("SHOW COLUMNS FROM `Emails`");
while($row = mysql_fetch_array($result)){
$Addresses[] = $row['Field'];}
$Subject = "Test";
$Message = "
Test
";
$Headers = array( EMPTY FOR SECURITY REASONS );
$Headers = implode( "\r\n" , $Headers );
$ChunkAddresses = 50;
$EmailChunkArray = array_chunk($Addresses, $ChunkAddresses);
$ArraySize = count ($EmailChunkArray);
$ChunkSize = 0;
ChunkLoop: {
$EmailChunkArrayLoop = $GLOBALS["EmailChunkArray"];
foreach ($EmailChunkArrayLoop[$GLOBALS["ChunkSize"]] as $ToChunkLoop) {
if ($GLOBALS["ChunkSize"] <= $GLOBALS["ArraySize"]) {
mail($ToChunkLoop,$GLOBALS["Subject"],$GLOBALS["Message"],$GLOBALS["Headers"]);
echo "This is the " . $GLOBALS["ChunkSize"] . " chunk. <br>";
} else if ($GLOBALS["ChunkSize"] == $GLOBALS["ArraySize"]){
exit();}
$GLOBALS["ChunkSize"]++;
break 1;}
}
if ($GLOBALS["ChunkSize"] != $GLOBALS["ArraySize"]){
echo "Test. <br>";
goto ChunkLoop;
} else {
echo "Finished! <br>";}
Create script that will only do one thing - send mail.
sendMail.php
<?php
// Get recipient from the argv array
$recipient = $_SERVER['argv'][1];
// Mail args
$subject = 'HELLOOOOOOO';
$message = 'BLablabla';
$headers = [...]; // optional or not
// Send it
mail($recipient, $subject, $message, $headers);
And inside of Your code where You do:
mail($ToChunkLoop,$GLOBALS["Subject"],$GLOBALS["Message"],$GLOBALS["Headers"]);
Replace with:
$recipient = escapeshellarg($ToChunkLoop);
exec("php /path/to/sendMail.php ".$recipient." > /dev/null &"); // that will call mail script and will not wait when execution will end
Feel free to adapt my code examples as You wish
P.S. this solution is for cases when You don't want to pay for normal batch mail sending, mail subscription or dedicated, vps services and have just small web hosting. (:
P.S.. it's not a brilliant solution, but done for requirements provided by question author

Cron job doesn't send email [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have a cron job set up on my hostgator server that returns a value of 1 (email sent), but doesn't actually send the email. When I call the php file manually in the browser, the email gets sent. It doesn't if run via cron.
Earlier this month, I moved my site from one server on hostgator to another server (on hostgator) so I could get SSL and a dedicated IP address. Since moving the site, the cron jobs work OK except for the part that sends the email (ie, database functions work fine). I've contacted hostgator tech support, but he thinks the problem is in my code.
Thinking that maybe my server info was incorrect, I switched to using smtp.gmail.com and using a gmail account to send the mail, but that didn't work either. Please help!
The cron job is set up like this:
* 7 * * * /opt/php56/bin/php /home/user/public_html/somefolder/sendmailcron.php
(While testing, I changed it to run every 2 minutes: */2 * * * * )
Here's the sendmailcron.php script:
<?php
$now = date("Y-m-d H:i:s");
$msgcontent = [];
$msgcontent['email'] = "recipient#example.com";
$msgcontent['name'] = "Recipient Name";
$msgcontent['textpart'] = "This is the text version of the email body.";
$msgcontent['htmlpart'] = "<p>This is the <strong>HTML</strong> version of the email body.</p>";
$msgcontent['subject'] = "Test email sent at " . $now;
$result = sendMyMail($msgcontent, "HTML");
exit();
function sendMyMail($msgcontent, $format="HTML") {
require_once '/home/user/public_html/somefolder/swiftmailer/lib/swift_required.php';
$result = 0;
$subject = $msgcontent['subject'];
$email = $msgcontent['email'];
if (strlen($email) == 0) {
return 0;
}
$name = $msgcontent['name'];
$emailbody = $msgcontent['textpart'];
$emailpart = $msgcontent['htmlpart'];
switch($format) {
case "TEXT":
$msgformat = 'text/plain';
break;
case "HTML":
$msgformat = 'text/html; charset=UTF-8';
break;
default:
$msgformat = 'text/html';
break;
}
$adminemailaddress = "me#mydomain.com";
$adminemailpwd = 'myadminpwd';
$sendername = 'My Real Name';
$transport = Swift_SmtpTransport::newInstance('mygator1234.hostgator.com', 465, "ssl")
->setUsername($adminemailaddress)
->setPassword($adminemailpwd)
;
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
if($format == "TEXT") {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailbody)
->setContentType($msgformat)
;
}
else {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailpart)
->setContentType($msgformat)
;
}
//This is where we send the email
try {
$result = $mailer->send($message); //returns the number of messages sent
} catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
return $result; //will be 1 if success or 0 if fail
}
?>
The return value is always 1, but no email is sent.
Any suggestions would be greatly appreciated!
Your cron job uses a different php.ini configuration file, than your browser uses.
Try running the cron job by disabling safe_mode, like this:
/opt/php56/bin/php -d safe_mode=Off /home/user/public_html/somefolder/sendmailcron.php
And check if the email is now sent.

PHP Mailer Script for sending Unlimited Mails

I am facing a problem with sending bulk emails to all my recipients (approx 10,000) It sends about 600 - 800 mails and then just stops without any reason. I am using a shared server.
Here is My Code.
<?php
#session_start();
if(!isset($_SESSION['uid'])){
echo "<html><head>";
echo "<script language=javascript>function load25(){
alert('........................You Must Login .........................');
window.location='email_login.html';}</script>";
echo "</head><body onload=load25()></body></html>";
die();
}
include "connection.php";
$uid=$_SESSION['uid'];
//var_dump($uid);
require_once('mail.message.php');
require_once('mail.info.php');
$email_id=uniqid();
$m="<html><body>";
$m.= $_POST['content'];
$subject= $_POST['subject'];
$m.="<img src='http://emailpro.in/mail/trackerimage.php?utm_source=gmail&utm_medium=email&utm_content=image&utm_campaign=services&campaignID=1&subscriberID=".$email_id."&subject=".$subject."' border='0' alt='' style='height:1px;width:1px' />";
$to1=$_POST['to'];
$username=$_POST['usid'];
$passwd=$_POST['ppwd'];
$replymailid=$_POST['repmid'];
$campname=$_POST['campname'];
//echo" $replymailid <BR> $campname";
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
$date1= $date->format( 'y/m/d H:i:s');
//echo $date1;
//$datetimee= date('y/m/d - H:i:s') ;
//date('l jS \of F Y h:i:s A');
//echo "Time Is $date ";
function nowhitespace($data)
{
return preg_replace('/\s/', '',$data);
}
$to2=nowhitespace($to1);
$b=rtrim($to2,',');
//Print_r($b);
$s=array();
$s=explode(",","$b");
$n=$_POST['no'];
//echo "The number of emails u have selected is $n<br />";
$s=array();
$s=explode(",","$b");
$s1=implode(",", $s);
$Email = new Email();
$Email->sender = $replymailid;
$Email->recipient=$s1;
$Email->subject =$subject;
$Email->message_text = "Hello!";
$Email->message_html = $m;
// send the email
$Courier = new Courier();
$sent = $Courier->send($Email);
$result=mysql_query("INSERT INTO sentmails VALUES('','$uid','$campname','$subject','$b','$n','$date1')");
/*if(isset($_POST['no'])!=" ")*/
if($n!="")
{
$rec = mysql_query("SELECT * from clientmailid where userid='$uid' limit $n");
$count = mysql_num_rows($rec);
// echo $count;
if($n!=0 && $count!=0 && $n<=$count)
{
// echo $n;
$recipients = mysql_query("SELECT * from clientmailid where userid='$uid' limit $n");
while($row = mysql_fetch_array($recipients))
{
$addresses[]= $row['emailid'];
//echo $addresses;
}
$to = implode(",", $addresses);
// print_r($to);
/* $Tos=array();
$Tos=explode(",","$to");
$Tos1=implode(",", $Tos);
*/ $Email->recipient=$to;
} else
{
echo '<html>';
echo '<head></head>';
echo '<body onload=load30()>';
echo '</body>';
echo'</html>';
echo "**Sorry You Don't have enough Email Credits**";
}
}
if ($sent != Courier::SEND_OK) {
echo "Mailer Error" ;
}
else {
if($n!=0 && $count!=0){
$n=$_POST['no'];
$recipients = mysql_query("SELECT * from clientmailid where userid='$uid' limit $n");
while($row = mysql_fetch_array($recipients))
{
$addresses[]= $row['emailid'];
$mid=$row['mid'];
$result13 = mysql_query("delete FROM clientmailid where mid='$mid' limit $n");
//echo $addresses;
}
}
echo"<script>alert('Thank u for using emailpro Your mails will be processed and will be sent shortly');</script>";
echo '<script> window.location="./dashboard.php";</script>';
}
?>
<script type="text/javascript">
function load30()
{
alert("Sorry u don't have enough email credits");
window.location='./tofill.php';
}
</script>
I know that we can send send unlimited mails through a shared server and I am sure there is something wrong either with my code or something with the server. Please guide me accordingly....
Thanks
I don't think there is anything wrong with your code, not because I can read it (please put clearer code on SO) but that it sends a random amount between 600-800 successfully. The following problems are most likely and one of them or both will solve the problem:
1) One of the potential reasons can be PHP timing out the script. Every script gets to run for a limited amount of time. If your script takes more time than that then PHP will simply kill the script. Typically that should cause an error being reported in the error logs. Check your apache error log messages - they might contain a hint.
Just add ini_set('max_execution_time', 0); in the top of your mailing script to test if this is the problem.
2) Could this be being caused by your local mail server? If you're sending out 10.000 emails in a short space of time, it might be assuming that it's spamming, and stop once you reach a certain amount. Try creating a mailing queue and sending in periodically.

How to loop every 3 minutes but script not sleep

I have a script for chat auto respond that uses while() to run, so it runs forever until it dies.
I want to be able to make it send a 'PING' message once every 3 minutes but still can do 'AUTO RESPOND' each message received.
The trouble is if i am using sleep(180) function for looping 'PING' message every 3 minute will make the 'AUTO RESPOND' every message be stop responding message because the script get sleep with sleep(180) function.
So what solution to make the script can do looping 'PING' message every 3 minutes but still can do 'AUTO RESPOND' every message at the same time.
What is possible ?
Did someone can help me with based on my script below ?
$this->connect();
while(!$this->isDisconnected()) {
$starts = $this->processUntil(array('message', 'session_start'));
foreach($starts as $go) {
switch($go[0]) {
case 'session_start':
$this->presence($status="Just Online !!!", $show="online");
break;
case 'message':
$filter = $show="online";
if($new['from'] == $filter) {
$sender = explode('#', $new['from']);
$this->message($new['from'], $body="AUTO RESPOND MESSAGE: Sorry $sender[0] Iam Not Here Right Now.", $type="chat");
}
$the_time = time();
$interval = 3*60;
while(true) {
if ($the_time + $interval >= time()) {
$this->message($myself, $body="PING !!!", $type="chat");
$the_time = time();
}
}
break;
}
}
}

PHP Script to send email with no timeout

I am using this code to send email to my list using my server.
after a while as my list of email is large, the script get timeout.
is there a solution to this problem?
other thing i don't want to overload the server. Is there a code i can add to my script to load each email with a time between each line?
here is the php script i am using
<?php
$emailaddress = file("email-list.txt"); // load from a flat file, assuming 1 email per line in the file
$emailsubject = "[title] title of my email";
$emailbody = file_get_contents("email-content.html");
$fromaddress = "my#3emailserver.com";
$i = count($emailaddress);
$z = 0;
// here we check how many email address's we have, if its is 0, then we don't start the email function
if ($i != 0)
{// start if
// Lets loop until we reach the count from email address arrar
while ($i != $z)
{// start while
// here we send the email to the varables from above, using the email array incrament
mail($emailaddress[$z], $emailsubject, $emailbody, "From: " .$fromaddress. "\nX-Mailer: PHP 4.x");
// lets echo out that the email was sent
echo $z + 1 . " out of " . $i . " emails sent. (" . $emailaddress[$z] . ")<br>";
// increment the array one, so we get a new email address from the array
++$z;
}// end while
}//end if
else
{//start else
// we echo out that no emails where found in the array and end the script
echo "Warning: No emails in array.";
}// end else
?>
use
// sleep for 10 seconds
sleep(10);
after mail fire.
By default in php.ini, max_execution_time is set to 30 seconds. (check this in your php.ini)
Use set_time_limit function to alter that time (0=NOLIMIT):
set_time_limit(0);
Or use ini_set function:
ini_set('max_execution_time', 0);

Categories