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;
}
}
?>
@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