1

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);


  ?>

5
  • Cron runs from another directory (possibly root), so you need to change your cd to the absolute path Commented Sep 24, 2021 at 13:49
  • If I understand it right: The script will execute not at it‘s own place... It will execute at the directory where the crontab is defined ? @aynber Commented Sep 24, 2021 at 14:38
  • Correct. If you've defined it in crontab -e, it will start in the user's directory, but if it's the master cron, then it won't be. It's always smart to use absolute paths when dealing with cron Commented Sep 24, 2021 at 14:48
  • Thank you now the cronjob workes perfectly (with absolut path) Commented Sep 24, 2021 at 15:47
  • An off-topic side note: You should definitely use systemd .timer units instead of cronjobs. They give you much more control and flexibility, security hardening options etc. Commented Sep 26, 2021 at 1:41

1 Answer 1

0

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");  
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this Explantation helped me very much :)
You're welcome! Happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.