Search code examples
phpbashcron

Cronjob with php script to execute bash command


I have a cronjob that executes a this php script. The check for the httpStatus works fine. The Big problem is the execution of the bash command. (else) Is there something wrong?

<?php
    $url = "https://xxx";

  $handle = curl_init($url);
  curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
  
  /* Get the HTML or whatever is linked in $url. */
  $response = curl_exec($handle);
  
  /* Check for 404 (file not found). */
  $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  
  if($httpCode == 200) {
      /* Handle 200 here. */
      $output = "Status 200 OK";
  }
  else{
      $output = shell_exec('cd public_html/redmine/ && bundle exec ruby bin/rails server -b webrick -e production -d');
      
  }
  
  curl_close($handle);
  
  /* Handle $response here. */

echo($output);


  ?>


Solution

  • I would recommend changing to an absolute path on the cd command, something like:

    cd /home/my-user/public_htm/redmine ...

    When you run a PHP script, the relative path is from where the script was executed and not the location of the PHP file.

    For example, if you are running php ./public_html/my-cronjob.php from inside of /home/my-user, the current working directory (CWD) would be /home/my-user instead of /home/my-user/public_html. Any cd command is executed relatively to your CWD.

    The current working directory can be checked with getcwd().

    You could achieve the same result by using __DIR__ which gives you the directory of the PHP file.

    if($httpCode == 200) {
        /* Handle 200 here. */
        $output = "Status 200 OK";
    } else {
        $serverDir = __DIR__ . "/public_html/redmine";
        $output = shell_exec("cd {$serverDir} && bundle exec ruby bin/rails server -b webrick -e production -d");  
    }