Skip to content
PHP Logo

What are the differences between running a PHP script in the console and through shell_exec in terms of directory paths?

When running a PHP script in the console, the current working directory is typically the directory where the script is located. However, when using shell_exec to run a PHP script, the current working directory may be different, leading to issues with relative paths. To solve this issue, you can use the __DIR__ magic constant to get the directory of the current script and construct absolute paths based on that.

php
// Get the directory of the current script
$scriptDir = __DIR__;

// Use the script directory to construct absolute paths
$filePath = $scriptDir . '/file.txt';

// Use shell_exec with the absolute path
$output = shell_exec("php $scriptDir/script.php");