Skip to content

Instantly share code, notes, and snippets.

@stevegrunwell
Created August 15, 2012 21:44
Show Gist options
  • Save stevegrunwell/3363975 to your computer and use it in GitHub Desktop.
Save stevegrunwell/3363975 to your computer and use it in GitHub Desktop.
Get current git HEAD using PHP
<?php
/**
* Get the hash of the current git HEAD
* @param str $branch The git branch to check
* @return mixed Either the hash or a boolean false
*/
function get_current_git_commit( $branch='master' ) {
if ( $hash = file_get_contents( sprintf( '.git/refs/heads/%s', $branch ) ) ) {
return $hash;
} else {
return false;
}
}
?>
@CaseyRo
Copy link

CaseyRo commented Sep 14, 2019

There seems to be a discrepancy in using this on a local git environment or a remote one (like in my case, using gitlab), where one is pointing to the current HEAD in ./git/HEAD, but in some other cases, it just gives you the SHA in .git/HEAD.

Since for me - the release number is only relevant on production, I've used the original instead of @dorantor's example.

@tps2015gh
Copy link

tps2015gh commented Nov 10, 2020

Thanks, I developer function for get current , git branch name

function get_current_git_branch(){
    $fname = sprintf( '.git/HEAD' );
    $data = file_get_contents($fname);   
    $ar  = explode( "/", $data );
    $ar = array_reverse($ar);
    return  trim ("" . @$ar[0]) ;
}

function get_current_git_datetime( $branch='master' ) {
      $fname = sprintf( '.git/refs/heads/%s', $branch );
      $time = filemtime($fname);
      if($time != 0 ){
          return date("Y-m-d H:i:s", $time);
        }else{
            return  "time=0";
      }
}

@ryanjbonnell
Copy link

ryanjbonnell commented Nov 19, 2021

An example adapted for use in a Laravel project:

/**
 * Attempt to Retrieve Current Git Commit Hash in PHP.
 *
 * @return mixed
*/
protected function getCurrentGitCommitHash()
{
    $path = base_path('.git/');

    if (! file_exists($path)) {
        return null;
    }

    $head = trim(substr(file_get_contents($path . 'HEAD'), 4));

    $hash = trim(file_get_contents(sprintf($path . $head)));

    return $hash;
}

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