Daniel
11-12-2009, 09:40 AM
Well, this was basically my first PHP script after BobboHobbo wanted something like this. I took that moment as an opportunity to start learning PHP. I based it off a template, which had about 7 lines in it, and built it from there.
At first, Tootoot222 helped me on one little tiny thing i read about, SQL Injections. He just told me to use mysql_real_escape_string to escape most injection attacks, so I rolled with it :cool:
After that, i had a significant amount of help from ss23 when he was online ( <3 ), suggestions and some help xD. Another major help was my trial and error :p. Simtoon kept asking me to check out http://thesimtoon.com/ for PHP help, but his website had nothing related to my questions :p
So, after about 2 weeks of development (on and off, firstly i spent like 1 hour a day on it (for about 2 days :p) then went to about 30 minutes, then back up because it was nearly finished) i present to you my Authorization system!:
Automatically creates the table and database if they don't exist, default password hashing is using the Secure Hashing Algorithm-2 (SHA-2) and can be fully customized (i.e. You can add your own salting method). It uses MySQLi (as suggested by ss23), so I'm not sure, but some MySQLi functions require PHP5 or greater (i think). Feel free to use, but keep credits in-tact please :)
Basically you can pick up what the variables in the "Script Setup" section mean, just by reading the examples on how to create an account or validate an account in the top section of the script :)
<?php
/*-------------------------
//
// -- Authorization system created by Mayazcherquoi
// -- Version 1.01
// -- Release 17/01/2010
//
-------------------------*/
/*-------------------------
// -- To create an account, you must
// -- supply the following (using
// -- default parametres):
// -- http://yourdomain.com/authorization.php?ins=1&usr=username&psw=password&anm=admin&apw=passw
// -- This will successfully create
// -- an account with those details.
//
// -- To identify an account, you must
// -- do the following:
// -- http://yourdomain.com/authorization.php?usr=username&psw=password
//
// Other then that, hope you enjoy
// the creation of this script
-------------------------*/
/*
Setup all the required global variables:
*/
//Administrator Details
$admName = "admin"; //Administrator account name?
$admPass = "passw"; //Administrator account password?
//Script Details
$pswhash = false; //Do you want to encrypt (hash) the password?
$usrImp = "usr"; //Username parametre variable?
$pswImp = "psw"; //Password parametre variable?
$hasImp = "hsh"; //Hashing parametre variable?
$insImp = "ins"; //Insert account parametre variable?
$anmImp = "anm"; //Administrator name account parametre variable?
$apwImp = "apw"; //Administrator password account parametre variable?
//MySQL Details
$sqlhost = "localhost"; //MySQL Database Host (leave localhost if you don't know)?
$sqlport = "3306"; //MySQL Database Port (default is 3306)?
$sqluser = "root"; //MySQL Username (default is root)?
$sqlpass = ""; //MySQL Password (default is none)?
$sqldbse = "cndb"; //MySQL Database name?
/*
NOTE: ONLY change these setting
IF the table DOESN'T exist yet.
*/
$maxUsrLnth = 16; //Maximum characters allowed in username (recommended at 16)?
$maxPswLnth = 225; //Maximum characters allowed in password (recommended at 40, leave at 40 if you're SHA1 hashing)?
// -- YOU CAN IGNORE THE REST -- \\
$bsHTML = "<!-- Script created by Mayazcherquoi\n Authorization Version: 1.01".
"\n Release Date: 17th January, 2010 -->\n".
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">".
"\n<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"".
"text/html;charset=utf-8\">\n <title>\n Mayazcherquoi's Autho".
"rization Script\n </title>\n </head>\n <body style=\"background-color: white;\">\n ".
"<font style=\"color: black; font-size:16px; font-family: Arial;\">\n ";
$enHTML = "\n </font>\n </body>\n</html>\n<!-- Script created by Mayazcherquoi\n".
"Authorization Version: 1.01\n Release Date: 17th January, 2010 -->\n\n";
/*
Simple hash algorithm.
Replace with your own if you want
(you can salt it in here too ;) ).
*/
function hashstr($thestring)
{
$sLen = strlen($thestring);
if($sLen == 0)
{
return hash("sha224", " ");
}
return hash("sha224", $thestring);
}
/*
Connect to the MySQL Database, if
can't connect, print's "Connection Error.".
*/
$cnection = new mysqli($sqlhost, $sqluser, $sqlpass, "", $sqlport);
if (mysqli_connect_errno()) {
die("Connection Error.");
}
/*
Convert the administrator username
and password to be able to use this
system.
*/
$admName = substr($cnection->real_escape_string(strtolower($admName)), 0, $maxUsrLnth);
$admPass = substr($cnection->real_escape_string(strtolower($admPass)), 0, $maxPswLnth);
/*
Get username and password,
protects from SQL injection,
converts them to lower-case
and hashes the password with
your custom algorithm.
*/
$username = substr($cnection->real_escape_string(strtolower($_GET[$usrImp])), 0, $maxUsrLnth);
if($pswhash) {
$password = substr(hashstr(strtolower($cnection->real_escape_string($_GET[$pswImp]))), 0, $maxPswLnth);
} else {
$password = substr(strtolower($cnection->real_escape_string($_GET[$pswImp])), 0, $maxPswLnth);
}
/*
Will select the database,
otherwise create the database,
otherwise "Database Error.".
*/
function cdatabase()
{
global $cnection;
global $cntdb;
global $sqldbse;
$cntdb = $cnection->select_db($sqldbse);
if(!$cntdb) {
$cntdb = $cnection->query("SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\"");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
$cntdb = $cnection->query("CREATE DATABASE `" . $sqldbse . "` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
$cntdb = $cnection->query("USE `" . $sqldbse . "`");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
}
return $cnection->select_db($sqldbse);
}
/*
Making sure that the table exists,
otherwise will create it.
*/
function ctable()
{
global $sqldbse;
global $cnection;
global $arrSQL;
global $maxUsrLnth;
global $maxPswLnth;
$sql = $cnection->query("SELECT 1 FROM users");
if(!$sql) {
if(strtolower($cnection->error) == "table '". $sqldbse . ".users' doesn't exist") {
$sql = $cnection->query("CREATE TABLE IF NOT EXISTS `users` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, " .
"`user` varchar(" . $maxUsrLnth . ") COLLATE utf8_bin NOT NULL, `pass` char(" . $maxPswLnth . ") COLLATE utf8_bin NOT NULL, " .
"UNIQUE KEY `id` (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2");
if(!$sql) {
die($bsHTML . "Table creation error." . $enHTML);
}
$sql = $cnection->query("SELECT 1 FROM users");
if(!$sql) {
die($bsHTML . "Table creation error." . $enHTML);
}
}
}
return $cnection->query("SELECT * FROM users LIMIT 1");
// return $cnection->query("SELECT 1 FROM users");
}
/*
Checks if table and database exist,
otherwise will create one. Otherwise
error.
*/
cdatabase();
ctable();
/*
Creates an account with the supplied
parametres. If this is creating the
Administrator account, it will ignore
script termination when finished.
*/
function createacc($usr, $psw) {
global $admName;
global $cnection;
if(cdatabase()) {
if(ctable()) {
$usreX = $cnection->query("SELECT * FROM users WHERE user = '" . $usr . "'");
if($usreX->num_rows > 0) {
if(!$usr == $admName)
die($bsHTML . "Account already exists." . $enHTML);
} else {
$r = $cnection->query("SELECT MAX(id) AS maxid FROM users")->fetch_assoc();
$hId = $r['maxid'] + 1;
$cnection->query("INSERT INTO users (id, user, pass) VALUES ('" . $hId . "', '" . $usr . "', '" . $psw . "')");
}
}
}
if($cnection->query("SELECT * FROM users WHERE user = \"" . $usr . "\"")->num_rows == 0) {
if(!$usr == $admName)
{
die($bsHTML . "Account creation error." . $enHTML);
} else
{
die($bsHTML . "Administrator account creation error." . $enHTML);
}
} else
if(!($usr == $admName))
die($bsHTML . "Account created successfully." . $enHTML);
}
/*
Checks if the administrator account
exists, otherwise will create it.
*/
$admExists = $cnection->query("SELECT * FROM users WHERE user = '" . $admName . "'");
if($cnection->fetch_row == 0) {
if($pswhash) {
createacc($admName, hashstr(strtolower($cnection->real_escape_string($admPass))));
} else {
createacc($admName, strtolower($cnection->real_escape_string($admPass)));
}
}
/*
If the hash parametre if present,
then will output the custom hash
function on the string supplied in
the hash parametre.
*/
if($_GET[$hasImp]) {
die($bsHTML . hashstr(strtolower($cnection->real_escape_string($_GET[$hasImp]))) . $enHTML);
}
/*
Checks for administrator account
penetration.
*/
if($username == $admName)
die($bsHTML . "You cannot check for authorization with the administrator username.\n<br>\n" .
"You can find your administrator account details within the first few lines of this PHP script.\n" . $enHTML);
/*
Checks to see if account insertation
is directed. Will then check all the
required parametres and their values.
Will create the account with variables
$username and $password as details if
no errors occurred.
*/
if($_GET[$insImp] == "1") {
if(!$_GET[$usrImp] || !$_GET[$pswImp] || !$_GET[$anmImp] || !$_GET[$apwImp]) {
die($bsHTML . "Invalid parametres for account creation." . $enHTML);
}
$sSQL = $cnection->query("SELECT * FROM users WHERE user =\"" . $username . "\"");
if($sSQL->num_rows > 0) {
die($bsHTML . "Account already exists." . $bsHTML);
}
$receiveanm = substr($cnection->real_escape_string(strtolower($_GET[$anmImp])), 0, $maxUsrLnth);
$receiveapw = substr($cnection->real_escape_string(strtolower($_GET[$apwImp])), 0, $maxPswLnth);
if($pswhash)
$receiveapw = hashstr($receiveapw);
if(($_GET[$anmImp] == $admName) && ($_GET[$apwImp] == $admPass))
createacc($username, $password);
}
/*
Makes sure database and table
exist (again) and checks whether
the account stored in variables
$username and $password exist.
"Successful." if all was successful,
"Invalid Password." if account exists
but the password was wrong, and
"Invalid Username." if the username
could not be found.
*/
if(cdatabase()) {
if(ctable()) {
$qSQL = $cnection->query("SELECT * FROM users WHERE user =\"" . $username . "\"");
if($qSQL->num_rows > 0) {
$arrSQL = $qSQL->fetch_assoc();
if($password == $arrSQL['pass']) {
echo $bsHTML . "Successful." . $enHTML;
} else {
die($bsHTML . "Invalid password." . $enHTML);
}
} else {
die($bsHTML . "Invalid username." . $enHTML);
}
}
}
?>
Thanks r!ch!e for leading me to find an error in the above script. I also fixed up the '[' brackets :)
Enjoy :D
*comments and constructive criticism please, as this was basically my first PHP script (discluding <?php echo "Hello World"; ?>, and other similar variants :p)*
At first, Tootoot222 helped me on one little tiny thing i read about, SQL Injections. He just told me to use mysql_real_escape_string to escape most injection attacks, so I rolled with it :cool:
After that, i had a significant amount of help from ss23 when he was online ( <3 ), suggestions and some help xD. Another major help was my trial and error :p. Simtoon kept asking me to check out http://thesimtoon.com/ for PHP help, but his website had nothing related to my questions :p
So, after about 2 weeks of development (on and off, firstly i spent like 1 hour a day on it (for about 2 days :p) then went to about 30 minutes, then back up because it was nearly finished) i present to you my Authorization system!:
Automatically creates the table and database if they don't exist, default password hashing is using the Secure Hashing Algorithm-2 (SHA-2) and can be fully customized (i.e. You can add your own salting method). It uses MySQLi (as suggested by ss23), so I'm not sure, but some MySQLi functions require PHP5 or greater (i think). Feel free to use, but keep credits in-tact please :)
Basically you can pick up what the variables in the "Script Setup" section mean, just by reading the examples on how to create an account or validate an account in the top section of the script :)
<?php
/*-------------------------
//
// -- Authorization system created by Mayazcherquoi
// -- Version 1.01
// -- Release 17/01/2010
//
-------------------------*/
/*-------------------------
// -- To create an account, you must
// -- supply the following (using
// -- default parametres):
// -- http://yourdomain.com/authorization.php?ins=1&usr=username&psw=password&anm=admin&apw=passw
// -- This will successfully create
// -- an account with those details.
//
// -- To identify an account, you must
// -- do the following:
// -- http://yourdomain.com/authorization.php?usr=username&psw=password
//
// Other then that, hope you enjoy
// the creation of this script
-------------------------*/
/*
Setup all the required global variables:
*/
//Administrator Details
$admName = "admin"; //Administrator account name?
$admPass = "passw"; //Administrator account password?
//Script Details
$pswhash = false; //Do you want to encrypt (hash) the password?
$usrImp = "usr"; //Username parametre variable?
$pswImp = "psw"; //Password parametre variable?
$hasImp = "hsh"; //Hashing parametre variable?
$insImp = "ins"; //Insert account parametre variable?
$anmImp = "anm"; //Administrator name account parametre variable?
$apwImp = "apw"; //Administrator password account parametre variable?
//MySQL Details
$sqlhost = "localhost"; //MySQL Database Host (leave localhost if you don't know)?
$sqlport = "3306"; //MySQL Database Port (default is 3306)?
$sqluser = "root"; //MySQL Username (default is root)?
$sqlpass = ""; //MySQL Password (default is none)?
$sqldbse = "cndb"; //MySQL Database name?
/*
NOTE: ONLY change these setting
IF the table DOESN'T exist yet.
*/
$maxUsrLnth = 16; //Maximum characters allowed in username (recommended at 16)?
$maxPswLnth = 225; //Maximum characters allowed in password (recommended at 40, leave at 40 if you're SHA1 hashing)?
// -- YOU CAN IGNORE THE REST -- \\
$bsHTML = "<!-- Script created by Mayazcherquoi\n Authorization Version: 1.01".
"\n Release Date: 17th January, 2010 -->\n".
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">".
"\n<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"".
"text/html;charset=utf-8\">\n <title>\n Mayazcherquoi's Autho".
"rization Script\n </title>\n </head>\n <body style=\"background-color: white;\">\n ".
"<font style=\"color: black; font-size:16px; font-family: Arial;\">\n ";
$enHTML = "\n </font>\n </body>\n</html>\n<!-- Script created by Mayazcherquoi\n".
"Authorization Version: 1.01\n Release Date: 17th January, 2010 -->\n\n";
/*
Simple hash algorithm.
Replace with your own if you want
(you can salt it in here too ;) ).
*/
function hashstr($thestring)
{
$sLen = strlen($thestring);
if($sLen == 0)
{
return hash("sha224", " ");
}
return hash("sha224", $thestring);
}
/*
Connect to the MySQL Database, if
can't connect, print's "Connection Error.".
*/
$cnection = new mysqli($sqlhost, $sqluser, $sqlpass, "", $sqlport);
if (mysqli_connect_errno()) {
die("Connection Error.");
}
/*
Convert the administrator username
and password to be able to use this
system.
*/
$admName = substr($cnection->real_escape_string(strtolower($admName)), 0, $maxUsrLnth);
$admPass = substr($cnection->real_escape_string(strtolower($admPass)), 0, $maxPswLnth);
/*
Get username and password,
protects from SQL injection,
converts them to lower-case
and hashes the password with
your custom algorithm.
*/
$username = substr($cnection->real_escape_string(strtolower($_GET[$usrImp])), 0, $maxUsrLnth);
if($pswhash) {
$password = substr(hashstr(strtolower($cnection->real_escape_string($_GET[$pswImp]))), 0, $maxPswLnth);
} else {
$password = substr(strtolower($cnection->real_escape_string($_GET[$pswImp])), 0, $maxPswLnth);
}
/*
Will select the database,
otherwise create the database,
otherwise "Database Error.".
*/
function cdatabase()
{
global $cnection;
global $cntdb;
global $sqldbse;
$cntdb = $cnection->select_db($sqldbse);
if(!$cntdb) {
$cntdb = $cnection->query("SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\"");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
$cntdb = $cnection->query("CREATE DATABASE `" . $sqldbse . "` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
$cntdb = $cnection->query("USE `" . $sqldbse . "`");
if(!$cntdb) {
die($bsHTML . "Database Error." . $enHTML);
}
}
return $cnection->select_db($sqldbse);
}
/*
Making sure that the table exists,
otherwise will create it.
*/
function ctable()
{
global $sqldbse;
global $cnection;
global $arrSQL;
global $maxUsrLnth;
global $maxPswLnth;
$sql = $cnection->query("SELECT 1 FROM users");
if(!$sql) {
if(strtolower($cnection->error) == "table '". $sqldbse . ".users' doesn't exist") {
$sql = $cnection->query("CREATE TABLE IF NOT EXISTS `users` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, " .
"`user` varchar(" . $maxUsrLnth . ") COLLATE utf8_bin NOT NULL, `pass` char(" . $maxPswLnth . ") COLLATE utf8_bin NOT NULL, " .
"UNIQUE KEY `id` (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2");
if(!$sql) {
die($bsHTML . "Table creation error." . $enHTML);
}
$sql = $cnection->query("SELECT 1 FROM users");
if(!$sql) {
die($bsHTML . "Table creation error." . $enHTML);
}
}
}
return $cnection->query("SELECT * FROM users LIMIT 1");
// return $cnection->query("SELECT 1 FROM users");
}
/*
Checks if table and database exist,
otherwise will create one. Otherwise
error.
*/
cdatabase();
ctable();
/*
Creates an account with the supplied
parametres. If this is creating the
Administrator account, it will ignore
script termination when finished.
*/
function createacc($usr, $psw) {
global $admName;
global $cnection;
if(cdatabase()) {
if(ctable()) {
$usreX = $cnection->query("SELECT * FROM users WHERE user = '" . $usr . "'");
if($usreX->num_rows > 0) {
if(!$usr == $admName)
die($bsHTML . "Account already exists." . $enHTML);
} else {
$r = $cnection->query("SELECT MAX(id) AS maxid FROM users")->fetch_assoc();
$hId = $r['maxid'] + 1;
$cnection->query("INSERT INTO users (id, user, pass) VALUES ('" . $hId . "', '" . $usr . "', '" . $psw . "')");
}
}
}
if($cnection->query("SELECT * FROM users WHERE user = \"" . $usr . "\"")->num_rows == 0) {
if(!$usr == $admName)
{
die($bsHTML . "Account creation error." . $enHTML);
} else
{
die($bsHTML . "Administrator account creation error." . $enHTML);
}
} else
if(!($usr == $admName))
die($bsHTML . "Account created successfully." . $enHTML);
}
/*
Checks if the administrator account
exists, otherwise will create it.
*/
$admExists = $cnection->query("SELECT * FROM users WHERE user = '" . $admName . "'");
if($cnection->fetch_row == 0) {
if($pswhash) {
createacc($admName, hashstr(strtolower($cnection->real_escape_string($admPass))));
} else {
createacc($admName, strtolower($cnection->real_escape_string($admPass)));
}
}
/*
If the hash parametre if present,
then will output the custom hash
function on the string supplied in
the hash parametre.
*/
if($_GET[$hasImp]) {
die($bsHTML . hashstr(strtolower($cnection->real_escape_string($_GET[$hasImp]))) . $enHTML);
}
/*
Checks for administrator account
penetration.
*/
if($username == $admName)
die($bsHTML . "You cannot check for authorization with the administrator username.\n<br>\n" .
"You can find your administrator account details within the first few lines of this PHP script.\n" . $enHTML);
/*
Checks to see if account insertation
is directed. Will then check all the
required parametres and their values.
Will create the account with variables
$username and $password as details if
no errors occurred.
*/
if($_GET[$insImp] == "1") {
if(!$_GET[$usrImp] || !$_GET[$pswImp] || !$_GET[$anmImp] || !$_GET[$apwImp]) {
die($bsHTML . "Invalid parametres for account creation." . $enHTML);
}
$sSQL = $cnection->query("SELECT * FROM users WHERE user =\"" . $username . "\"");
if($sSQL->num_rows > 0) {
die($bsHTML . "Account already exists." . $bsHTML);
}
$receiveanm = substr($cnection->real_escape_string(strtolower($_GET[$anmImp])), 0, $maxUsrLnth);
$receiveapw = substr($cnection->real_escape_string(strtolower($_GET[$apwImp])), 0, $maxPswLnth);
if($pswhash)
$receiveapw = hashstr($receiveapw);
if(($_GET[$anmImp] == $admName) && ($_GET[$apwImp] == $admPass))
createacc($username, $password);
}
/*
Makes sure database and table
exist (again) and checks whether
the account stored in variables
$username and $password exist.
"Successful." if all was successful,
"Invalid Password." if account exists
but the password was wrong, and
"Invalid Username." if the username
could not be found.
*/
if(cdatabase()) {
if(ctable()) {
$qSQL = $cnection->query("SELECT * FROM users WHERE user =\"" . $username . "\"");
if($qSQL->num_rows > 0) {
$arrSQL = $qSQL->fetch_assoc();
if($password == $arrSQL['pass']) {
echo $bsHTML . "Successful." . $enHTML;
} else {
die($bsHTML . "Invalid password." . $enHTML);
}
} else {
die($bsHTML . "Invalid username." . $enHTML);
}
}
}
?>
Thanks r!ch!e for leading me to find an error in the above script. I also fixed up the '[' brackets :)
Enjoy :D
*comments and constructive criticism please, as this was basically my first PHP script (discluding <?php echo "Hello World"; ?>, and other similar variants :p)*