Tagged: PHP

PHP: Better way to manage your cron rather than writing all in crontab

In PHP , if we are writing the scheduled tasks in core php,

then, we need to setup the individual cron in either crontab in linux or schedule task in windows.

Whenever there are number of crons in a product across multiple platform , it hard to setup all and manage
and one more thing, somehow managing cron is also outside of the code or developer scope in traditional way.

However, the following is not the best way to manage, but still a better way rather than scattered code.

Code : –

<?php
// list of crons
$crons = array(
// command line script
    array(
        "time" => '00 02 * * *',
        'execute' => '/usr/bin/php ' . '/var/www/html/test/cron.php > /dev/null'
    ),
// get url
    array(
        "time" => '*/5 * * * *',
        'execute' => 'wget -O - ' . 'http://developerck.com/test/cron.php'
    )

);

if (empty($_GET['web'])) {
    runcron($crons);
} else {
    printcrons($crons);
}

/*
 * functions to print and run crons
 *
 * if you want to print the list of crons
 * printcrons($crons)
 *
 * runcron($crons) will trye to execute all setup crons
 *
 * (With the above code , you can pass query parameter web to true , ?web=1 to print)
 *
 */

// Printing Crons
function printcrons($crons)
{
    $str = "<table>";
    foreach ($crons as $e) {
        $str .= "<tr>";
        $str .= "<td>" . implode(" ", $e) . "</td>";
        $str .= "</tr>";
    }
    $str .= "</table>";
    echo $str;
}

// function to run crons
function runcron($crons)
{
    // check if shell_exec function is allowd or disabled
    if (function_exists('shell_exec')) {
        foreach ($crons as $c) {
            $time = time();
            // check if it is the time to execute
            if (is_time_cron($time, $c['time'])) {
                // if you wnat to print the command
                echo $command = $c['execute'];
                $str = PHP_EOL . "||" . date("Y-m-d H:i:s") . "||" . $command . PHP_EOL;
                // log all the things under cron.txt
                @file_put_contents("cron.txt", $str, FILE_APPEND);
                // // execute commands
                @shell_exec($command);
            }
        }
    } else {
        echo "shell_exec function does not exist or disabled";
    }
}

// function to check if it is the time to run the cron
function is_time_cron($time, $cron)
{
    $cron_parts = explode(' ', $cron);
    if (count($cron_parts) != 5) {
        // checking for * * * * *
        return false;
    }
    
    $c = explode(' ', $cron);
    $min = $c[0];
    $hour = $c[1];
    $day = $c[2];
    $mon = $c[3];
    $week = $c[4];
    $to_check = array(
        'min' => 'i',
        'hour' => 'G',
        'day' => 'j',
        'mon' => 'n',
        'week' => 'w'
    );
    
    $ranges = array(
        'min' => '0-59',
        'hour' => '0-23',
        'day' => '1-31',
        'mon' => '1-12',
        'week' => '0-6'
    );
    
    foreach ($to_check as $part => $c) {
        $val = $$part;
        $values = array();
        
        /*
         * For patters like 0-23/2
         */
        if (strpos($val, '/') !== false) {
            // Get the range and step
            list ($range, $steps) = explode('/', $val);
            
            // Now get the start and stop
            if ($range == '*') {
                $range = $ranges[$part];
            }
            list ($start, $stop) = explode('-', $range);
            
            for ($i = $start; $i <= $stop; $i = $i + $steps) {
                $values[] = $i;
            }
        } /*
           * For patters like :
           * 2
           * 2,5,8
           * 2-23
           */
        else {
            $k = explode(',', $val);
            
            foreach ($k as $v) {
                if (strpos($v, '-') !== false) {
                    list ($start, $stop) = explode('-', $v);
                    
                    for ($i = $start; $i <= $stop; $i ++) {
                        $values[] = $i;
                    }
                } else {
                    $values[] = $v;
                }
            }
        }
        
        if (! in_array(date($c, $time), $values) and (strval($val) != '*')) {
            return false;
        }
    }
    
    return true;
}

The above code has three functions .

  • is_time_cron () : check whether it is time to run the cron or not
  • printcrons() : if you just want to print the scheduled crons
  • runcron() : you can pass the array of the cron. this function is only needed to call and and it will internally call is_time_cron.
 array("time" => '00 02 * * *',
 'execute' => '/usr/bin/php ' . '/var/www/html/test/cron.php > /dev/null')

Time is the scheduled time at which the cron will run and execute contains the command which needs to be run.

the following https://crontab.guru/ will help you understand the logic behind time ‘ * * * * *’

How important it is to upgrade your AMP(Apache, PHP, Mysql) Stack?

Whenever we have a project/product to develop using LAMP stack, the following are the major factors in Platform stack version selection

  • Availability of software(PHP, MYSQL, APACHE)
  • Configuration/Setup of developer machines
  • Hosting server restriction
  • Skill set of employees

Let’s say you start an application today with the latest stable release of stack , then it will be outdated in a year or more as technology is updating regularly.

Q: – So the question is, is it necessary to update the product/ project or to guide your client about the required updates for that ?

My answer will be Yes.

Now you can question that do you understand the aftermath for this,

  • Upgradation requires the efforts
  • Effort includes Development effort, Testing Effort, Skillset of Resources
  • Effort create cost

So, are you sure you we should do the upgrades and guide our client for this.

I will again say , Yes.

Q: – So tell me Why it so necessary to upgrades while we can save the cost?

I will start with an example,

Think that you are a Civil Engineer, and you build the bridges. Let’s say you build a bridge, and ask yourself, is this one time job to build that bridge or owner need to maintain that half-yearly/yearly/bi-early/ so that it stay for long and secure.”

Mainly, There are two types of upgrades

  • Major :   It may require refactoring of application [Generally Call Upgrades]
  • Minor : In 90% of cases, minor updates does not break anything, that is an improvement or fixes of bugs of any software.[Generally called Updates]

So, Minor upgrades does not include a major cost, however, major upgrades may have major cost factor.

If you are concerned about the security or your application includes the payment, I will recommend that you must have your application stack up-to-date, However, My Practical experience will suggest you to do the upgrades once it is stable and you had the review/feedback from the market so that your have more visibility in advance before updating.

Q:- It may be that your application does not contain any payment information, so do you still need to update that?

Yes, it is advised to keep your application updated to keep it less vulnerable ( I am saying less as upgrades itself can’t prevent all the loopholes), To protect your user data and your valuables and it can save a lot money from ransomware or hackers.

So is this all about security ?

No this is more than security,

Up-gradation provides protection from existing loopholes, apart from that, It also helps you in optimisation the performance of your site.

Here is an example of bench marking of popular PHP framework laravel over various php version.https://dzone.com/articles/php-56-vs-php-7-performance-benchmarks-with-larave,

You can see that how much the up-gradation help in optimisation and resource utilisation that is also a cost saving for long term. So your cost of up-gradation can be covered from here while you utilise all the benefits of up gradation.

This is also not about PHP only. You must upgrade all the stack from time-time where it is OS , Apache Web server or Mysql.

Every Software has their END OF LIFE and upgrades cycle and it is different for each software. How ever One must deploy all the security and BUG Fixes patch time-time that does not require major effort and before the END OF LIFE of that software one must upgrade the software.

Following articles shows how  the cyber attacks cost the company  

Cybercrime will remain a large-scale concern for years to come. From 2019–2023E, approximately $5.2 trillion in global value will be at risk from cyberattacks, creating an ongoing challenge for corporations and investors alike https://www.weforum.org/agenda/2019/11/cost-cybercrime-cybersecurity/

Make sure to check the support from Vendor for your software.

PHP Support as on 5 Jan 2020
  • Apache Httpd : Apache httpd 2.2 is End-of-Life since December 2017 and should not be used. Apache 2.4 should be utilised. https://httpd.apache.org/