Authentication class using cookies or sessions


/ Published in: PHP
Save to your folder(s)

Here is an old Auth class that i made :)


Copy this code and paste it in your HTML
  1. <?php
  2. /*
  3. #
  4. # Copyright Iulian Ciobanu (CIGraphics) 2009
  5. # Please leave the copyright and email intact.
  6. #
  7.  
  8. # DATABASE TABLE:
  9.  
  10. CREATE TABLE `users` (
  11.   `id` int(11) NOT NULL AUTO_INCREMENT,
  12.   `user` varchar(200) NOT NULL,
  13.   `password` varchar(40) NOT NULL,
  14.   `email` varchar(200) NOT NULL,
  15.   PRIMARY KEY (`id`)
  16. ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
  17.  
  18. # LETS INSERT SOME DATA FOR TESTING PURPOSES:
  19. INSERT INTO `users` (`id`, `user`, `password`, `email`) VALUES (1, 'user', '20ccbe71c69cb25e4e0095483cb63bd394a12b23', '[email protected]');
  20.  
  21. # FOR TESTING PURPOSES:
  22. The user is: user
  23. The password is: 123456
  24.  
  25. # USAGE:
  26.  
  27. $auth = new Auth('database', 'user', 'password', 'host'); // This must be placed at the top of your document you don't need to start the session this script will do it.
  28. $auth->type = session or cookie; // If you want to use sessions you don't need to write it else write cookie.
  29. $auth->emailAuth = false or true; // If you want users to login with email instead of username set it to true or don't write this because is set to false by default
  30. $auth->minval = integer; // The minimum chars for username. Write this only if you want to change the value because it's set by default 6.
  31. $auth->maxval = integer; // The maximum chars for username. Write this only if you want to change the value because it's set by default 22.
  32. $auth->minpass = integer; // The minimum chars for password. Write this only if you want to change the value because it's set by default 6.
  33. $auth->salt = 'LOTS OF CHARS OF ANY TYPE'; // Change this. This is for security hashing. I strongly recommed to change this in the script or write this with other random chars.
  34.  
  35. $auth->login($user, $password); // Place this in the part where you get the post vars from your login forms
  36.  
  37. $auth->logout(); // Place this after $auth = new Auth(..) or if you setup type and emailAuth place it below them. Like in example. If you add it without that then you will never be able to login
  38.  
  39. $auth->error(); // Place this in your document. This function will display the errors from validation and other like mysql errors.
  40.  
  41.  
  42.  
  43. */
  44. class Auth {
  45.  
  46. var $type = 'cookie';
  47. private $connection;
  48. private $errors = array();
  49. var $minval = 6;
  50. var $maxval = 22;
  51. var $minpass = 6;
  52. var $salt = '#@()DIJK#)(F#&*()DS#@JKS)@(I()#@DU)*(&@#)(#U)J';
  53. var $emailAuth = false;
  54.  
  55. function __construct($db, $user, $pass, $host) {
  56. if ( $this->type == 'session' ) {
  57. }
  58. $this->mysqlconnect($user, $pass, $host);
  59. $this->mysqldb($db);
  60. $this->check();
  61. }
  62.  
  63. private function mysqlconnect($user, $pass, $host) {
  64. $conn = @mysql_connect($host, $user, $pass);
  65. if ( !$conn ) {
  66. die('There is a problem with your mysql connection');
  67. } else {
  68. $this->connection = $conn;
  69. }
  70. }
  71.  
  72. private function mysqldb($db) {
  73. if ( !@mysql_select_db($db, $this->connection) ) {
  74. die('The database doesn\'t exist');
  75. }
  76.  
  77. }
  78.  
  79. private function query($sql) {
  80. $result = @mysql_query($sql, $this->connection);
  81. if ( !$result ) {
  82. $this->errors[] = 'SQL Error';
  83. } else {
  84. return $result;
  85. }
  86. }
  87.  
  88. private function fobj($result) {
  89. return mysql_fetch_object($result);
  90. }
  91.  
  92. private function fnum($result) {
  93. return mysql_num_rows($result);
  94. }
  95.  
  96. private function fescape($value) {
  97. return mysql_real_escape_string($value);
  98. }
  99.  
  100. public function login($user, $pass) {
  101. $email = $this->emailAuth;
  102. $err = false;
  103. $user = strtolower($user);
  104. $password = $this->encrypt($pass);
  105. if ( $email == true ) {
  106. if ( !$this->email($user) ) {
  107. $this->errors[] = 'Email invalid.';
  108. $err = true;
  109. } else {
  110. $col = 'email';
  111. }
  112. } else {
  113. if ( !$this->name($user) ) {
  114. $this->errors[] = 'Name invalid. Min chars: '.$this->minval.'. Max chars: '.$this->maxval;
  115. $err = true;
  116. } else {
  117. $col = 'user';
  118. }
  119. }
  120. if ( strlen($pass) < $this->minpass ) {
  121. $this->errors[] = 'Password min value is 6 chars.';
  122. $err = true;
  123. }
  124.  
  125. if ( $err == false ) {
  126.  
  127. $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($user));
  128. $result = $this->query($sql);
  129. if ( $this->fnum($result) == 0 ) {
  130. $this->errors[] = ucfirst($col).' doesn\'t exist.';
  131. } else {
  132. $row = $this->fobj($result);
  133. if ( $row->password == $password ) {
  134. if ( $this->type == 'session' ) {
  135. $this->set_session($col, $user);
  136. $this->set_session('password', $password);
  137. } elseif ( $this->type == 'cookie' ) {
  138. $this->set_cookie($col, $user);
  139. $this->set_cookie('password', $password);
  140. }
  141. header('Location: ./auth.php');
  142. } else {
  143. $this->errors[] = 'Incorrect password';
  144. }
  145. }
  146.  
  147. }
  148. }
  149.  
  150. private function encrypt($value) {
  151. $enc = md5($this->salt.md5($value));
  152. return sha1($enc);
  153. }
  154.  
  155. // Email validation
  156. private function email($email) {
  157. $reg = "#^(((([a-z\d][\.\-\+_]?)*)[a-z0-9])+)\@(((([a-z\d][\.\-_]?){0,62})[a-z\d])+)\.([a-z\d]{2,6})$#i";
  158. if ( !preg_match($reg, $email) ) {
  159. return false;
  160. } else {
  161. return true;
  162. }
  163. }
  164.  
  165. // Name validation
  166. private function name($name) {
  167. $min = $this->minval - 2;
  168. if ( !preg_match("#^[a-z][\da-z_]{".$min.",".$this->maxval."}[a-z\d]\$#i", $name) ) {
  169. return false;
  170. } else {
  171. return true;
  172. }
  173. }
  174.  
  175. private function set_session($name, $value) {
  176. $_SESSION[$name] = $value;
  177. }
  178.  
  179. private function destroy_session() {
  180. }
  181.  
  182. private function set_cookie($name, $value, $time = 3600 ) {
  183. setcookie($name, $value, time()+$time, '/');
  184. }
  185.  
  186. private function destroy_cookie($name) {
  187. setcookie($name, '', time()-1, '/');
  188. }
  189.  
  190. public function logout() {
  191. if ( $this->emailAuth == false ) {
  192. $col = 'user';
  193. } else {
  194. $col = 'email';
  195. }
  196. if ( $this->type == 'session' ) {
  197. $this->destroy_session();
  198. } elseif ( $this->type == 'cookie' ) {
  199. $this->destroy_cookie('password');
  200. $this->destroy_cookie($col);
  201. }
  202. header ( 'Location: ./auth.php' );
  203. }
  204.  
  205. private function check() {
  206. if ( $this->emailAuth == false ) {
  207. $col = 'user';
  208. } else {
  209. $col = 'email';
  210. }
  211. if ( $this->type == 'cookie' ) {
  212. if ( isset($_COOKIE['password']) ) {
  213. $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_COOKIE[$col]) );
  214. $result = $this->query($sql);
  215. $row = $this->fobj($result);
  216. if ( $row->{$col} !== $_COOKIE[$col] || $row->password !== $_COOKIE['password'] ) {
  217. $this->logout();
  218. }
  219. }
  220. } elseif ( $this->type == 'session' ) {
  221. if ( isset($_SESSION['password']) ) {
  222. $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_SESSION[$col]) );
  223. $result = $this->query($sql);
  224. $row = $this->fobj($result);
  225. if ( $row->{$col} !== $_SESSION[$col] || $row->password !== $_SESSION['password'] ) {
  226. $this->logout();
  227. }
  228. }
  229. }
  230. }
  231.  
  232. public function error() {
  233. if ( is_array($this->errors) && !empty($this->errors) ) {
  234. echo '<div style="border:1px solid #CCC; background-color:#FAFAFA; color:#FF0000">';
  235. foreach ( $this->errors as $value ) {
  236. echo $value."<br />";
  237. }
  238. echo '</div>';
  239. }
  240. }
  241.  
  242. public function isLoggedIn() {
  243. $ret = false;
  244. if ( $this->emailAuth == false ) {
  245. $col = 'user';
  246. } else {
  247. $col = 'email';
  248. }
  249. if ( $this->type == 'cookie' ) {
  250. if ( isset($_COOKIE['password']) ) {
  251. $ret = true;
  252. }
  253. } elseif ( $this->type == 'session' ) {
  254. if ( isset($_SESSION['password']) ) {
  255. $ret = true;
  256. }
  257. }
  258. return $ret;
  259. }
  260.  
  261. }
  262. ?>
  263.  
  264.  
  265.  
  266.  
  267.  
  268. Example:
  269. login.php
  270. <?php
  271. include 'class_auth.php';
  272. $auth = new Auth('database', 'user', 'password', 'host'); // This order: Database User Password Host
  273.  
  274. if ( isset($_GET['logout']) ) {
  275. $auth->logout();
  276. }
  277.  
  278. if ( isset($_POST['login']) ) {
  279. $auth->login($_POST['user'], $_POST['pass']); // This order: User/Email Password True/False (if you want to use email as auth
  280. }
  281. ?>
  282.  
  283. HERE HTML STUFF
  284.  
  285. <?php if ( $auth->isLoggedIn() ) : ?>
  286. <h1>Welcome</h1>
  287. <a href="<?=$_SERVER['PHP_SELF'];?>?logout=true">Logout</a>
  288. <?php else : ?>
  289. <h1>Please login</h1>
  290. <form action="<?=$_SERVER['PHP_SELF'];?>?auth" method="post">
  291. <input type="text" name="user" /> User/Email<br />
  292. <input type="password" name="pass" /> Password<br />
  293. <input type="submit" name="login" value="Login" />
  294. </form>
  295. <?php $auth->error(); endif; ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.