[PHP]is_executable関数の使い方と実践例【完全ガイド2025】

PHP

PHPでファイルやディレクトリの実行権限をチェックしたいとき、is_executable関数が重要な役割を果たします。この記事では、is_executable関数の基本的な使い方から実践的な活用例まで、詳しく解説していきます。

is_executable関数とは?

is_executable関数は、指定されたファイルまたはディレクトリが実行可能かどうかを判定するPHPの組み込み関数です。実行権限があるかどうかをboolean値(true/false)で返します。

基本構文

bool is_executable(string $filename)
  • パラメータ: $filename – チェックしたいファイルまたはディレクトリのパス
  • 戻り値: 実行可能な場合はtrue、そうでない場合はfalse

基本的な使い方

シンプルな例

<?php
$file = '/usr/bin/php';

if (is_executable($file)) {
    echo "ファイルは実行可能です";
} else {
    echo "ファイルは実行できません";
}
?>

複数ファイルのチェック

<?php
$files = [
    '/bin/bash',
    '/usr/bin/python3',
    '/etc/passwd',
    './script.sh'
];

foreach ($files as $file) {
    $status = is_executable($file) ? '実行可能' : '実行不可';
    echo "{$file}: {$status}\n";
}
?>

実践的な活用例

1. スクリプト実行前の権限チェック

<?php
function executeScript($scriptPath) {
    // ファイルの存在確認
    if (!file_exists($scriptPath)) {
        throw new Exception("スクリプトファイルが見つかりません: {$scriptPath}");
    }
    
    // 実行権限の確認
    if (!is_executable($scriptPath)) {
        throw new Exception("スクリプトに実行権限がありません: {$scriptPath}");
    }
    
    // スクリプト実行
    $output = shell_exec($scriptPath);
    return $output;
}

try {
    $result = executeScript('./backup.sh');
    echo "バックアップ完了: " . $result;
} catch (Exception $e) {
    echo "エラー: " . $e->getMessage();
}
?>

2. システムコマンドの可用性チェック

<?php
class SystemChecker {
    private $requiredCommands = [
        'git' => '/usr/bin/git',
        'node' => '/usr/bin/node',
        'npm' => '/usr/bin/npm',
        'composer' => '/usr/local/bin/composer'
    ];
    
    public function checkSystemRequirements() {
        $results = [];
        
        foreach ($this->requiredCommands as $name => $path) {
            $results[$name] = [
                'path' => $path,
                'available' => is_executable($path),
                'which' => $this->findCommand($name)
            ];
        }
        
        return $results;
    }
    
    private function findCommand($command) {
        $path = shell_exec("which {$command} 2>/dev/null");
        return $path ? trim($path) : null;
    }
}

$checker = new SystemChecker();
$requirements = $checker->checkSystemRequirements();

foreach ($requirements as $name => $info) {
    $status = $info['available'] ? '✓' : '✗';
    echo "{$status} {$name}: {$info['path']}\n";
}
?>

3. 動的なスクリプト実行システム

<?php
class ScriptRunner {
    private $scriptsDir;
    
    public function __construct($scriptsDir = './scripts/') {
        $this->scriptsDir = rtrim($scriptsDir, '/') . '/';
    }
    
    public function getExecutableScripts() {
        $scripts = [];
        
        if (!is_dir($this->scriptsDir)) {
            return $scripts;
        }
        
        $files = scandir($this->scriptsDir);
        
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            
            $fullPath = $this->scriptsDir . $file;
            
            if (is_file($fullPath) && is_executable($fullPath)) {
                $scripts[] = [
                    'name' => $file,
                    'path' => $fullPath,
                    'size' => filesize($fullPath),
                    'modified' => filemtime($fullPath)
                ];
            }
        }
        
        return $scripts;
    }
    
    public function runScript($scriptName) {
        $scriptPath = $this->scriptsDir . $scriptName;
        
        if (!is_executable($scriptPath)) {
            throw new Exception("スクリプトが実行できません: {$scriptName}");
        }
        
        $output = shell_exec($scriptPath . ' 2>&1');
        return $output;
    }
}

// 使用例
$runner = new ScriptRunner('./scripts/');
$executableScripts = $runner->getExecutableScripts();

echo "実行可能なスクリプト一覧:\n";
foreach ($executableScripts as $script) {
    echo "- {$script['name']} ({$script['size']} bytes)\n";
}
?>

注意すべきポイント

1. ファイルの存在確認との組み合わせ

is_executableは存在しないファイルに対してもfalseを返すため、ファイルが存在しないのか、実行権限がないのかを区別したい場合は、file_existsと組み合わせて使用します。

<?php
function checkFileStatus($file) {
    if (!file_exists($file)) {
        return "ファイルが存在しません";
    }
    
    if (!is_executable($file)) {
        return "実行権限がありません";
    }
    
    return "実行可能です";
}

echo checkFileStatus('./script.sh');
?>

2. Windowsでの動作

Windows環境では、ファイル拡張子に基づいて実行可能性が判定されます。.exe.bat.cmdなどの拡張子を持つファイルが実行可能と判定されます。

<?php
// Windows環境での例
$files = [
    'C:\Windows\System32\notepad.exe',
    'C:\Windows\System32\ping.exe',
    'script.bat'
];

foreach ($files as $file) {
    if (is_executable($file)) {
        echo "{$file} は実行可能です\n";
    }
}
?>

3. セキュリティ上の考慮事項

ユーザー入力を直接is_executableに渡す場合は、パストラバーサル攻撃を防ぐために適切な検証を行う必要があります。

<?php
function safeIsExecutable($filename) {
    // 基本的な検証
    $filename = basename($filename);
    $allowedDir = '/safe/scripts/';
    $fullPath = $allowedDir . $filename;
    
    // パスが想定されたディレクトリ内にあるかチェック
    $realPath = realpath($fullPath);
    if ($realPath === false || strpos($realPath, realpath($allowedDir)) !== 0) {
        return false;
    }
    
    return is_executable($realPath);
}
?>

パフォーマンスの考慮事項

is_executableはファイルシステムにアクセスするため、大量のファイルをチェックする場合はパフォーマンスに影響を与える可能性があります。必要に応じてキャッシュを実装することを検討しましょう。

<?php
class ExecutableChecker {
    private $cache = [];
    private $cacheTimeout = 60; // 60秒間キャッシュ
    
    public function isExecutable($file) {
        $cacheKey = md5($file);
        
        if (isset($this->cache[$cacheKey])) {
            $cached = $this->cache[$cacheKey];
            if (time() - $cached['time'] < $this->cacheTimeout) {
                return $cached['result'];
            }
        }
        
        $result = is_executable($file);
        $this->cache[$cacheKey] = [
            'result' => $result,
            'time' => time()
        ];
        
        return $result;
    }
}
?>

まとめ

is_executable関数は、PHPでファイルの実行権限をチェックする際の重要なツールです。基本的な使い方から実践的な活用例まで理解することで、より安全で効率的なPHPアプリケーションを開発できるようになります。

特に以下の点を覚えておきましょう:

  • ファイルの存在確認と組み合わせて使用する
  • Windows環境では拡張子ベースで判定される
  • ユーザー入力の検証を忘れずに行う
  • 大量のファイルをチェックする場合はパフォーマンスを考慮する

これらのポイントを押さえて、is_executable関数を効果的に活用してください。

タイトルとURLをコピーしました