1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルスクリプト内でphpファイルを実行したい

Posted at

こんにちは!エンジニアの篠原です:penguin:

先日、業務でシェルスクリプトを作成していて
phpファイルを実行したいときがあり調べた結果を
備忘録として残したいと思います。

目次

1.phpファイルを準備
2.シェルスクリプトを作成
3.シェルスクリプトの動作確認
4.【おまけ】引数をphpファイルに渡す
5.【おまけ】エラーハンドリングとログ出力
6.まとめ

1.phpファイルを準備

まず、実行したいPHPファイルを作成または準備します。

sample.php
<?php
echo "PHPファイルが実行されました!\n";

2.シェルスクリプトを作成

次に、PHPファイルを実行するシェルスクリプトを作成します。

#!/bin/bash

# PHPの実行ファイルのパスを確認
PHP_PATH="/usr/bin/php"

# PHPスクリプトのパス
PHP_SCRIPT="/home/username/scripts/sample.php"

# PHPスクリプトを実行
$PHP_PATH $PHP_SCRIPT

# または、phpコマンドがPATHにある場合は以下でOK
# php $PHP_SCRIPT

3.シェルスクリプトの動作確認

まずシェルスクリプトを実行可能にするため、実行権限を付与します。

chmod +x /home/username/scripts/run_php.sh

では、実際に動作確認してみます。

/home/username/scripts/run_php.sh
出力結果
PHPファイルが実行されました!

無事、phpファイルが実行できました:clap:

4.【おまけ】引数をphpファイルに渡す

ここからはおまけですが、
phpファイルに引数を渡して実行したい場合は
以下のように書きます。

シェルスクリプト
#!/bin/bash

PHP_PATH="/usr/bin/php"
PHP_SCRIPT="/home/username/scripts/sample.php"

# 引数を指定
ARG1="hello"
ARG2="world"

# PHPスクリプトを引数付きで実行
$PHP_PATH $PHP_SCRIPT $ARG1 $ARG2
sample.php
<?php
// コマンドライン引数を取得
$args = $_SERVER['argv'];

// スクリプト名を除外
array_shift($args);

// 引数を表示
foreach ($args as $index => $arg) {
    echo "引数" . ($index + 1) . ": " . $arg . "\n";
}
出力結果
引数1: hello
引数2: world

5.【おまけ】エラーハンドリングとログ出力

実行結果やエラーをログファイルに出力したい場合は
以下のように書きます。

シェルスクリプト
#!/bin/bash

PHP_PATH="/usr/bin/php"
PHP_SCRIPT="/home/username/scripts/sample.php"

# ログファイルのパス
LOG_FILE="/home/username/scripts/php_sample.log"

# PHPスクリプトを実行し、出力をログに記録
$PHP_PATH $PHP_SCRIPT >> $LOG_FILE 2>&1

6.まとめ

今回は、シェルスクリプトでphpファイルを実行する方法をまとめました。
cronと組み合わせることで定期的に実行することもできますし
何かと便利です:thumbsup:

以上、篠原でした:penguin:

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?