Posted By

cigraphics on 05/04/10


Tagged

mysql auth class php session cookie


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

karp13
dantreacy
tux-world


Authentication class using cookies or sessions


 / Published in: PHP
 

Here is an old Auth class that i made :)

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

Report this snippet  

You need to login to post a comment.