In a recent project, I am finding way to display current git branch on the backend dashboard.
Without a application dependent library, executing CLI
git seems to be the fastest way.
i.e. The exactly same syntax as we use in bash/cmd/powershell.
$currentBranch = exec('git rev-parse --abbrev-ref HEAD');
However, it worked in production/staging Linux machine, but not in local Windows machine.
It does work if I specify the absolute path
C:\Program Files\Git\bin\git.exe, but it’s not optimal because it will be machine dependent.
After a while, I figure out the environment
PATH variable is missing in Windows that cause
git not being picked up.
The trick is, add this line before
exec call to:
putenv('PATH=' . $_SERVER['PATH']);