970_90

Wednesday, 22 January 2014

Manage Cron Job with PHP - SSH2 Connection

Manage Cron Job with PHP - SSH2 Connection

Today, Cron play very vital role in our website. It reduce the lots of manual work like update the record, Caching the pages, Remove not-required data etc.


Following are use of Cron Job
  1. Update Database records
  2. Copy/Move data from one server to another server
  3. Caching the data for enhance the website performance
  4. Remove the Redundancy data
  5. Remove the un-necessary data.


If there are too-many cron jobs in our web application that its hard to manage the cron jobs through crontabs. Also sometimes Compmay Owner/Manger wants to mange the cron jobs through the Admin Panel.  

Here is sample code with use of which you can mange the cron jobs from PHP. Now you can add/update/delete the cron job from PHP.



        /** check ssh2 connection**/
        if (!function_exists("ssh2_connect")){
            die('ssh2 is not installed');
        }
        /** check ssh2 connection**/
        
        if (!($con = ssh2_connect("www.example.com", 22))) {
            echo "Domain Not exist";
        } else {
            // try to authenticate with username root, password secretpassword
            if (!ssh2_auth_password($con, "username", "password")) {
                echo "credentials is In-Correct";
            } else {
                // execute a command
                if (!($stream = ssh2_exec($con, "ls -al"))) {
                    echo "Execution Failed";
                } else {
                    /** Read output */
                    stream_set_blocking($stream, true);
                    $data = "";
                    while ($buf = fread($stream, 4096)) {
                        $data .= $buf;
                    }
                    fclose($stream);
                    
                    echo $data;
                     /** Read output */
                }
            }
        }



No comments:

Post a Comment