Skip to content

Instantly share code, notes, and snippets.

@billymoon
Created October 30, 2011 10:34
Show Gist options
  • Save billymoon/1325769 to your computer and use it in GitHub Desktop.
Save billymoon/1325769 to your computer and use it in GitHub Desktop.
function to authenticate users from within php against linux user accounts on the server
/* Need to add www-data to group shadow (and restart apache)
$ sudo adduser www-data shadow
$ sudo /etc/init.d/apache2 restart
Needs whois to be installed to run mkpasswd
$ sudo apt-get install whois
Assumes that sha-512 is used in shadow file
*/
function authenticate($user, $pass){
// run shell command to output shadow file, and extract line for $user
// then spit the shadow line by $ or : to get component parts
// store in $shad as array
$shad = preg_split("/[$:]/",`cat /etc/shadow | grep "^$user\:"`);
// use mkpasswd command to generate shadow line passing $pass and $shad[3] (salt)
// split the result into component parts
$mkps = preg_split("/[$:]/",trim(`mkpasswd -m sha-512 $pass $shad[3]`));
// compare the shadow file hashed password with generated hashed password and return
return ($shad[4] == $mkps[3]);
}
// usage...
if(authenticate('myUsername','myPassword')){
// logged in
} else {
// not valid user
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment