使用 php 脚本执行 bash 命令的 Cronjob
Cronjob with php script to execute bash command
我有一个执行此 php 脚本的 cronjob。 httpStatus 的检查工作正常。最大的问题是 bash 命令的执行。 (else)有什么问题吗?
<?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);
?>
我建议在 cd
命令中更改为绝对路径,例如:
cd /home/my-user/public_htm/redmine ...
当您 运行 一个 PHP 脚本时,相对路径是脚本执行的位置,而不是 PHP 文件的位置。
例如,如果您从 /home/my-user
内部 运行ning php ./public_html/my-cronjob.php
,当前工作目录 (CWD) 将是 /home/my-user
而不是 /home/my-user/public_html
.任何 cd
命令都是相对于您的 CWD 执行的。
当前工作目录可以用getcwd()检查。
您可以通过使用 __DIR__
获得相同的结果,它为您提供 PHP 文件的目录。
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");
}
我有一个执行此 php 脚本的 cronjob。 httpStatus 的检查工作正常。最大的问题是 bash 命令的执行。 (else)有什么问题吗?
<?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);
?>
我建议在 cd
命令中更改为绝对路径,例如:
cd /home/my-user/public_htm/redmine ...
当您 运行 一个 PHP 脚本时,相对路径是脚本执行的位置,而不是 PHP 文件的位置。
例如,如果您从 /home/my-user
内部 运行ning php ./public_html/my-cronjob.php
,当前工作目录 (CWD) 将是 /home/my-user
而不是 /home/my-user/public_html
.任何 cd
命令都是相对于您的 CWD 执行的。
当前工作目录可以用getcwd()检查。
您可以通过使用 __DIR__
获得相同的结果,它为您提供 PHP 文件的目录。
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");
}