Run php script monthly on windows based server - php

I need your help to run following php script automatically on 05th day of the every month. Currently I run this manually. Is this possible using schedule task?
Also I don't have admin access to the web server. Therefore cannot use third party automation tools.
PS:
Is it possible to schedule this in a local machine with windows 7 xampp environment and then later update remote db?
session_start();
if($_SESSION['log'] != "log" || $_SESSION['type'] != "***"){
header("Location: ***.php");
}
require_once('conf.php');
date_default_timezone_set('Asia/Kolkata');
$date = date("j"); //get current date
$today = date("d-m-Y");
$now = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
if ($date === 5){
//get interest rate
$sql = mysql_query("SELECT Rate FROM Interest WHERE Ref = 'Loan' ORDER BY Date DESC LIMIT 1");
$r = mysql_fetch_assoc($sql);
$rate = $r['Rate'];
//check for not settled loans
$check = mysql_query("SELECT LID FROM Registry WHERE Status = 0");
if (mysql_num_rows($check) > 0){
while ($list = mysql_fetch_assoc($check)) { // while there are rows to be fetched...
//*** Start Transaction ***//
mysql_query("BEGIN");
$loanID = $list['LID'];
//get loan data
$sql = mysql_query("SELECT Registry.Amount, SUM(Account.Total) AS Paid, SUM(Account.Interest) AS intPaid FROM Registry LEFT JOIN Account ON Registry.LID = Account.LID WHERE Registry.Status = 0 AND Account.Auto = 0 AND (Account.LID = '$loanID') GROUP BY Account.LID");
$r = mysql_fetch_assoc($sql);
$amount = $r['Amount']; //loan amount
$paid = $r['Paid']; //sum of paid
$intPaid = $r['intPaid']; //sum of interest paid
//get sum of monthly automatically updated interest
$sql = mysql_query("SELECT SUM(Interest) AS Interest FROM Account WHERE Payment = 0 AND Auto = 1 AND LID = '$loanID'");
$r = mysql_fetch_assoc($sql);
$autoInt = $r['Interest'];
$total = ($amount + $autoInt); //total to be paid
$balance = ($total - $paid); //with no interest
if ($paid >= $balance){
// echo "Loan completed <br/>";
}else{
$int = ($balance * $rate) / 100;
$update = mysql_query("INSERT INTO Account (LID, Date, Interest, Total, Auto) VALUES ('$loanID', NOW(), '$int', '$int', 1)") or die(mysql_error());
if (! $update){
//*** RollBack Transaction ***//
mysql_query("ROLLBACK");
// $_SESSION['error'] = "Interest saving failed.!";
echo "Loan ID: " . $loanID . ", Interest: Rs. " . $int . "/= - Update Failed.!<br>";
}else{
//*** Commit Transaction ***//
mysql_query("COMMIT");
// $_SESSION['error'] = "Interest saved successfully";
echo "Loan ID: " . $loanID . ", Interest: Rs. " . $int . "/= - Update Succeeded.!<br>";
}
}
}
}
}else{
echo "Monthly Interest can be update only by 05th day of the month.!";
}

I dont think at needs admin permissions
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/at.mspx?mfr=true
EDIT:
or even try MySQL Events
http://dev.mysql.com/doc/refman/5.1/en/events.html
It looks all database work which should be easily do able

If it is a publicly accesseable web server, you can use a cronjob service like https://www.cronjobservice.net/. After registration you enter an url and the time they shall call it. I advice using multiple of those services for the case one fails. (your script must execute on first call and exit on subsequent calls from other services.)
Please be sure to properly deal with .htaccess and make sure to have no security relevant output.

Have you asked the peoples that are hosting your site if they have a solution?
Most hosting companies have solutions for this (even on Windows servers)
If the hosting company has no solution for this (what I seriously doubt) you can call the script externally from another server that has cron possibilities or have it called by the first visitor on that day.
I any case you will want to include a check in your script that your script only runs on the set date (you already have that) and also make sure that calling the script more than once on that day is no problem.
PS : if the script is called by the first visitor you will have to consider the fact that you could not have any visitor that particular day, so the script will have to run whenever the next visitor comes along.

If you don't have administrative access to Windows, you won't be able to create a scheduled task. Your only alternative is to create some sort of custom task component in your application that checks / stores the last time a script was run. The problem with this is that it relies on user activity and it may not run on the exact date that you want it to.
The other alternative is to find Linux hosting so that you can avail of Cron.

Related

MySQL table not updating through PHP cron job at specified time

I am working on an Android App which has a MySQL database which contains a table that has all the login details of each user.In that table I have column named "Status" which is initially assigned to 0 for every user.Everyday when the user logs in to his account and submits the data(clicks the submit button) the status is changed to 1.And every night at 12 AM the status should be reset to 0.Also, if the user doesnot submit the data until 10 AM for a day, a row should be automatically inserted to the MySQL table with a column value as "No Records" for the particular user whose status is still 0.So,I have a created a PHP file which runs as a cron job in cpanel. The PHP file checks the time every hour. And the current time 12 AM and 10 AM, it should do the required changes.But I am not getting the required result with my PHP script.The script is given below:
<?php
require "connection.php";
$get_time = "select date_format(NOW(), '%H:%i A') as current_daily_date from dual;";
$convert_time = mysqli_query($connect,$get_time);
$php_time = mysqli_fetch_assoc($convert_time);
$final_time = $php_time["current_daily_date"];
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
$d = $dateTime->format("H:i A ");
$e = $dateTime->format("d/m/y");
echo $d;
$s = '00:00';
$g = strtotime($s);
$p = date('H:i A',$g);
echo $p;
$c = '10:00';
$q = strtotime($c);
$r = date('H:i A',$q);
echo $r;
if($d == $p) {
$run = "UPDATE login SET status = 0;";
$connect->query($run);
echo "Status updated";
}
else if($d == $r) {
$second_run = "INSERT into attendance (name,date,attendance) VALUES ((SELECT name from login where status = 0 ), '$e' , 'No Records');";
$connect->query($second_run);
echo "Marked as No Records";
}
else {
echo "Not the correct time to change the status.";
}
$connect->close();
?>
I have set my email for the cron job so that I get the output to my mail. But even at 12 AM ,the table did not update.
The output was:
00:00 AM 00:00 AM10:00 AMNot the correct time to change the status.
I don't know where I am going wrong.Can anyone please check and let me know what is the issue?
The format of the INSERT SELECT is incorrect:
$second_run = "INSERT into attendance (name,date,attendance) SELECT name, ****, **** from login where status = 0";
You don't need the VALUES bit and I'm not sure what the end segment was at all. You also are trying to insert 3 values whilst only providing one, I've put ****'s in there where you need to put your other values.
You should also turn on error reporting in your script if you didn't get any errors from it as this would have been an error.
error_reporting(E_ALL);
ini_set('display_errors', 1);

php - phpMailer Cron add's an email to the queue while it shouldn't

I have a script that periodically (every ~5 minutes) requests a bunch of data from an API and possibly sends a email.
However I recently got contacted by the server administrator that there a huge amount of queued mails which will never be sent because of the Cron.
However as it stands right now it should never send the emails because it should never pass the if-statements in which the mailing code is placed.
Script more or less does the same thing twice, but with some different emails:
/* Paging - Every ~15 minutes, during non-working-times, for all dashboards that have pagerservice enabled. */
$queryPagerservice = mysqli_query($dbcon, "SELECT `id`, `text` FROM `dashboard` WHERE `pagerservice`=true AND (`last_pager` < NOW() - INTERVAL ".PAGER_INTERVAL." MINUTE OR `last_pager` IS NULL)");
$timeNow = date("Gi");
while ($pagerservice = mysqli_fetch_array($queryPagerservice, MYSQLI_ASSOC)) {
echo '1.'; //Does the script hit this code?
$issues = new Issues($pagerservice['id'], 'all', $dbcon);
$array = $issues->getIssues();
if ((count($array['aaData']) > 0) && ($timeNow > WORK_START && $timeNow < WORK_END)) {
mysqli_query($dbcon, "UPDATE `dashboard` SET `last_pager`=NOW() WHERE `id`='".$pagerservice['id']."'");
$date = date('d-m-Y H:i:s');
$message = "There are ".count($array['aaData'])." problems in '".$pagerservice['text']."'.";
echo '2.'; //Does the script hit this code?
require_once('phpmailer/PHPMailerAutoload.php');
$pagerMail = new PHPMailer;
$pagerMail->isSMTP();
$pagerMail->Host = MAILSERVER_ADDRESS;
$pagerMail->Port = MAILSERVER_PORT;
$pagerMail->setFrom('pagerservice#example.com', 'EXAMPLE Pager');
$pagerMail->addReplyTo('noreply#example.com', 'No Reply');
$pagerMail->addAddress(PAGE_EMAIL, 'pagerservice');
$pagerMail->addAddress(PAGER_PHONE.'#'.PAGER_PROVIDER, 'pagerservice');
$pagerMail->Subject = 'pagerservice';
$pagerMail->Body = $message;
$pagerMail->AltBody = $message;
$pagerMail->send();
}
}
/* Notifications - Every ~15 minutes, during working hours, for all dashboards that have notifications enabled. */
$queryNotification = mysqli_query($dbcon, "SELECT `id`, `text` FROM `dashboard` WHERE `notification`=true AND (`last_notification` < NOW() - INTERVAL ".NOTIF_INTERVAL." MINUTE OR `last_notification` IS NULL)");
$timeNow = date("Gi");
while ($notifications = mysqli_fetch_array($queryNotification, MYSQLI_ASSOC)) {
echo '3.'; //Does the script hit this code?
$issues = new Issues($notifications['id'], 'all', $dbcon);
$array = $issues->getIssues();
if ((count($array['aaData']) > 0) && ($timeNow > WORK_START && $timeNow < WORK_END)) {
mysqli_query($dbcon, "UPDATE `dashboard` SET `last_notification`=NOW() WHERE `id`='".$notifications['id']."'");
$date = date('d-m-Y H:i:s');
$message = "(Notif) There are ".count($array['aaData'])." problems in '".$pagerservice['text']."'.";
echo '4.'; //Does the script hit this code?
require_once('phpmailer/PHPMailerAutoload.php');
$notifMail = new PHPMailer;
$notifMail->isSMTP();
$notifMail->Host = MAILSERVER_ADDRESS;
$notifMail->Port = MAILSERVER_PORT;
$notifMail->setFrom('notifications#example.com', 'EXMAPLE Notificator');
$notifMail->addReplyTo('noreply#example.com', 'No Reply');
$notifMail->addAddress(NOTIF_EMAIL, 'notifications');
$notifMail->Subject = 'notification';
$notifMail->Body = $message;
$notifMail->AltBody = $message;
$notifMail->send();
}
}
Attempted fix: I moved the require_once() call to within the if-statement. This didn't fix it.
There is no other code in the script that is in any way related to sending email's. And the code that is e-mail related isn't executed (as shown by the fact that neither 1., 2., 3. nor 1. is echoed).
I am looking for any tips as to what can cause the cron script to queue an email that is never sent by the SMTP server.
Cron jobs have no user interface, so if the script outputs anything to the stderror or stdoutput it will cause the cron system to generate an email, to contain that output. This is how you would know your cron is having problems, or how you monitor things like "I did 10 things this run" type of stuff.
It looks to me as if your script has some kind of output either reporting errors or doing your echo '1.' debugging code or something similiar.
First I would check all the code you say it is running for anything like echo or print etc etc, anything that would normally write info to the terminal, and remove/rethink it.
Then change the cron's config to send these emails to a valid email address that you actually monitor, so you know when your script is trying to tell you something.

Error in script sending automatic birthday wish to a registered user in php

I have written the script of sending automatic e-mail for a given date. I have already set up the cron job to execute this once a day for a given time. But it is not working. Can anyone show me the error here. I'm really new to this.
What I'm really supposed to do is to send an automatic email to a user on their birthday
<?php
$host="mysql117.000webhost.com/";//hostname
$username="abc";//mysql_username
$password="123";//mysql_password
$dbname="abc";//Database name
$tbl_name="customer_info";//table name
$date = date("2005-09-23"); //here my date format in my DB is 2010-09-30
$link = mysqli_connect('$host','$username','$password','$dbname');
if($link && mysqli_select_db('$dbname', $link))
{
$grabBday = "SELECT b_day,DATE_FORMAT(b_day,'2015-%m-%d') FROM customer_info where b_day = '2002-09-24'";
//here it will take the name of the person whose bday is on a particular date,I just hard coded this date to check if this is working
if($rs = mysqli_query($link, $grabBday))
{
while(mysqli_fetch_array($rs))
{
mail('abc92#yahoo.com', 'HAPPY BIRTHDAY', 'Many Happy Returns of the day');
}
}
} ?>
I am seeing logical difference as you are searching where b_day=$date where $date='2015-09-23' but dob can be '2002-09-23' or '1997-09-23' etc. so you will not get desired output, so you can change your query as per below if everything other than it is fine.
SELECT * FROM
tbl_name
WHERE CONCAT(YEAR(CURDATE()),DATE_FORMAT(b_day,'-%m-%d')) = $date

PHP MySQL Deactivating premium membership after a certain amount of time?

I have just recently worked out how to use PayPal IPN to initiate a premium membership when users pay a certain amount for it. Once the user clicks upgrade account, they are directed to PayPal to pay, then the IPN kicks in to update the database to show that the user is premium. I was hoping to have this last for a certain amount of time before their account is returned to normal, yet not sure how to do that? For example, they upgrade, 2 years later, a MySQL update is triggered to return their account to average. Here is the IPN script I am using:
<?php
include 'core/init.php';
//DONT CHANGE THESE VARIABLES
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$receiver_email = $_POST['receiver_email'];
$username = $_POST['custom'];
if($payment_status =="Completed")
{
$purchase_check = mysql_query("SELECT premium FROM users WHERE username='$username'");
while($row = mysql_fetch_assoc($purchase_check))
{
$paid = $row['premium'];
}
if($paid=="0")
{
if($receiver_email=="aidan6141#hotmail.co.uk")
{
if($payment_amount=="6.99" && $payment_currency=="GBP")
{
$update_premium = mysql_query("UPDATE users SET premium='1' WHERE username='$username'");
}
}
}
}
else
{
echo "Access Denied!";
}
?>
I am thinking using my BASIC idea of PHP that I might add a value of "upgrade_date" to the database as a timestamp and then add into my code:
mysql_query("UPDATE users SET upgrade_date=CURDATE() WHERE username='$username'");
So updating the date when they upgrade shouldn't be an issue, the issue is how can I recall that information so in 2 years after the time stamp, they are issued back to an average member? I was also hoping to show a countdown date or something so they know how long they have left on their account?
Any help would be appreciated, thanks!
Why don't use unix timestamp instead of using boolean value in the database?
you can just say that the field premium in your database will save the expiration of premium membership
and then you can do the check to see if the current time stamp is greater than the value saved in the field premium then it's expired ... if it is Null or 0 he never been premium, and if it's less than the saved value then his membership is valid and then you can calculate the difference between current timestamp and the saved one to see how much longer it still has to expire.
Why not have in your DB
upgraded = tinyint: to store a 0 for not upgraded and a 1 for upgraded
upgraded_date = datetime: to store the date this was done
Then set-up a cron job to run (maybe a few times a day or just check as the user logs in) to check if the time has expired, if it has reset 'upgraded' to 0
you maybe need an else condition to check the years.
like that:
while($row = mysql_fetch_assoc($purchase_check))
{
$paid = $row['premium'];
$timestamp_start = $row['upgrade_date'];
$timestamp_end = date("Y/m/d");
$difference = abs($timestamp_end - $timestamp_start);
$years = floor($difference / (365*60*60*24));
}
if($paid=="0")
{
if($receiver_email=="aidan6141#hotmail.co.uk")
{
if($payment_amount=="6.99" && $payment_currency=="GBP")
{
$update_premium = mysql_query("UPDATE users SET premium='1' WHERE username='$username'");
}
}
}else if($years == 2){ do update here and set premium to 0}
else{do what you like here}
}
else
{
echo "Access Denied!";
}

send reminder emails with php and mysql WITHOUT cron-job?

I just made a php script that will send email reminders to admins of a website 2 days before an appointment begins. I was going to automate the script to run through a cron job, only to realise who I am hosting with (crazy domains) does NOT appear to have Cron Jobs
Is there ANY way of doing this without cron-jobs? I do not mind going to a different service provider if that is the case; I have done quite a bit of searching around, and my understanding so far is that I need Cron Jobs for these types of things?
Here is the script I did so far:
<?php include "../connect-to-database.php"; ?>
<?php
$date = date("Y-m-d");
$mod_date = strtotime($date."+ 2days");
$newDate = date("m/d/Y",$mod_date);
$sqlCommand = "SELECT * FROM eventcalender WHERE eventDate='$newDate'" ;
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if ($count >= 1){
while($row = mysql_fetch_array($query)){
$ID = $row["ID"];
$schedule_title = $row["Title"];
$schedule_description = $row["Detail"];
$importance_level = $row["importance_level"];
$meeting_datetime = $row["eventDate"];
$contacts_involved = $row["contacts_involved"];
$meeting_occurred = $row["meeting_occurred"];
$mid = mysql_insert_id();
$search_output .= "<ul>
<li>
<h4>".$schedule_title."</h4>
<p><b>Time: ".$meeting_datetime."</b></p>
<p>People/Persons involved: ".$contacts_involved."</p>
<p>Meeting Occurred?: ".$meeting_occurred."</p>
<a href='uniqueMeeting.php?ID=".$ID."'>View more details of this meeting</a>
<p><a href='editschedulePage.php?mid=$ID'>Edit This Meeting</a></p>
<p><a href='scheduleList.php?deleteid=$ID'>Delete this meeting</a></p>
</li><br/>
</ul>";
$sendMail = true;
}
}
if($sendMail){
$admin = "SELECT * FROM admin" ;
$queryAdmin = mysql_query($admin) or die(mysql_error());
$adminCount = mysql_num_rows($queryAdmin);
$recipients = array();
if ($count >= 1){
while($row = mysql_fetch_array($queryAdmin)){
$subject ='A-CRM; UpComing Activities';
$msg = $search_output;
$to = $row['email_address'];
mail($to, $subject, $msg);
}
}
}
?>
Yes I do realise I am an absolute horrible person for NOT using mysqli, and I will start to as soon as I finish this website
If the site you're building is visited frequently, you can keep a timestamp (or datetime or whatever) in your database holding the next time the script has to run. Then include the script in your website (every page or just a selection them).
If the current time is equal or greater than the time in the database, run the script and set the time in the database to the value the script has to run next. In this way, the script will be executed by one of the visitors of the site, without them knowing.
Replace
php include "../connect-to-database.php";
with
php include dirname(__DIR__) . "/connect-to-database.php";
Try to add some Observer which will check whether there is a need to send mails.
For example - add into your init file (maybe index.php)
<?php include DIR ."send_mail.php" ?> // your file that you describe in the question.
It will add an additional query to DB since the check will be executed every time the user comes on the page.
I hope it will help you to resolve your issue.
Very simply and effective way using crons. The crons are very simple you will set up date and time cron automatically runs your file. This is guide to using crontab: http://www.adminschoice.com/crontab-quick-reference/

Categories