Created
August 15, 2012 21:44
-
-
Save stevegrunwell/3363975 to your computer and use it in GitHub Desktop.
Get current git HEAD using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
?> |
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.
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";
}
}
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
Reference to current git HEAD is stored in
.git/HEAD
and first parameter for sprintf on line 8 should be taken from there:Example contents:
So it should be something like
or