Search code examples
phpregexcron

PHP - Save crontab to the database


I have a variable that contains a list of 3 jobs that can be created in linux and I would like to save each line of work in my database:

$jobs = """
0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
"""
$array = explode(" ", $jobs);
$job = new Job;
$job->min = $array[0];
$job->hour = $array[1];
$job->day_month = $array[2];
$job->mes = $array[3];
$job->day_week = $array[4];
$job->command = "/bin/bash";
$job->save();

The problem that is occurring for me is that I am only managing to save the first line. The other lines are not saving, and I think it is because there is an enter between them.

Second question is how to use a regular expression to get only the command for my job tar -zcf /var/backups/home.tgz / home / that has spaces but I wanted to save the entire command in a table just called "command".


Solution

  • The $array will contain all words separated with a space.

    [
     "0",
     "5",
     "*",
     "*",
     "1",
     "tar",
     "-zcf",
     "var/backups/home.tgz",
     "home\n0",
     "5",
     "*",
     "*",
     "1",
     ...
    ]
    

    You need to split the lines and loop through them.

    For the second question; use array_slice to get the remaining items from the array and then join them with implode.

    $jobs = "
    0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
    0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
    0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
    ";
    
    $lines = explode("\n", trim($jobs));
    
    foreach ($lines as $line) {
      $array = explode(" ", $line);
      $job = new Job;
      $job->min = $array[0];
      $job->hour = $array[1];
      $job->day_month = $array[2];
      $job->mes = $array[3];
      $job->day_week = $array[4];
      $job->command = implode(" ", array_slice($array, 5));
      $job->save();
    }