Skip to content

Instantly share code, notes, and snippets.

@jeroenvdgulik
Last active November 10, 2023 09:07
Show Gist options
  • Save jeroenvdgulik/701942 to your computer and use it in GitHub Desktop.
Save jeroenvdgulik/701942 to your computer and use it in GitHub Desktop.
Output the current branch in your PHP application
<?php
# Git branch output in PHP
exec('git symbolic-ref HEAD', $output);
$branch = end(explode('/', $output[0])));
@entitycs
Copy link

entitycs commented Aug 23, 2018

exec('git symbolic-ref HEAD', $output);
$branch = end(explode('/', $output[0]));

@relipse
Copy link

relipse commented May 22, 2019

This produces a Notice

$t = explode(...)
$branch = end($t);

to fix

@yuseferi
Copy link

yuseferi commented Sep 8, 2020

just use

$branch = trim(shell_exec('git rev-parse --abbrev-ref HEAD'));

@peter-gribanov
Copy link

just use

$branch = trim(shell_exec('git branch --show-current'));

@entitycs
Copy link

entitycs commented Dec 2, 2022

--show-current was not available in 2018, but going forward, it looks much nicer.

@VladSavitsky
Copy link

VladSavitsky commented Jun 12, 2023

To get sub-module branch name or when multiple git repos are in use:

$path = 'path/to/folder/with/git/repo';
$branch = trim(shell_exec('cd "${PWD}' . $path . '"; git rev-parse --abbrev-ref HEAD'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment