Jump to content

Utility classes


justsomeguy
 Share

Recommended Posts

I'm working on an application that I'm using a few classes for that other people might find useful. These are for PHP5 only, they would have to be rewritten to work with PHP4.This is my session class. You can call this something other than tc_lms_session if you want to:

<?phpclass tc_lms_session{  public $userid = 0;		 // the user ID will be non-zero if a user is logged in  public $username = '';	  // the username  public $fullname = '';	  // the user's full name  private $password = '';  public $userdata = false;   // the entire record from the users table in the database  public $error = '';		 // the error message  public $error_field = '';   // the field that caused the error (e.g. username, password, etc)  public $main_admin = false; // is the user an admin  function __construct($u = '', $p = '')  {	session_start();	if (isset($_SESSION['userid']))	{	  $this->userid = $_SESSION['userid'];	  $this->userdata = $_SESSION['userdata'];	  $this->username = $this->userdata['username'];	  $this->fullname = $this->userdata['fname'] . ' ' . $this->userdata['lname'];	  $this->main_admin = $this->userdata['main_admin'];	}	if ($u != '')	{	  $this->username = $u;	  $this->password = $p;	  $this->login();	}  }  function login($u = '', $p = '')  {	global $db;	if ($u != '')	{	  $this->username = $u;	  $this->password = $p;	}	$db->sql("SELECT * FROM users WHERE username = %s");	$db->add_param($this->username);	$result = $db->select();	if (!$result)	{	  $this->error_field = 'username';	  $this->error = 'The username was not found.';	  return false;	}	if ($this->password != $result[0]['password'])	{	  $this->error_field = 'password';	  $this->error = 'The password was not correct.';	  return false;	}	if ($result[0]['active'] == 0)	{	  $this->error_field = 'username';	  $this->error = 'The user account is not active.';	  return false;	}	$now = time();	$db->update('users', array('last_login' => $now, 'last_ip' => "'" . $_SERVER['REMOTE_ADDR'] . "'"), "id={$result[0]['id']}");	$result[0]['last_login'] = $now;	$result[0]['last_ip'] = $_SERVER['REMOTE_ADDR'];	$this->userid = $result[0]['id'];	$this->fullname = $result[0]['fname'] . ' ' . $result[0]['lname'];	$this->userdata = $result[0];	$this->main_admin = $result[0]['main_admin'];	$this->error = '';	$this->error_field = '';	$_SESSION['userid'] = $this->userid;	$_SESSION['userdata'] = $this->userdata;	return true;  }  function logout()  {	$_SESSION = array();	$this->userid = 0;	$this->userdata = false;	session_destroy();  }}?>

This is my database class. Again, you could rename the class if necessary:

<?phpclass tc_lms_database{  private $host = '';  private $user = '';  private $pass = '';  private $db = '';  private $conn = false;  public $sql_stmt = '';  public $params = false;  private $result = false;  private $rowset = false;  function __construct($h = '', $u = '', $p = '', $d = '')  {	if ($h != '')	{	  $this->host = $h;	  $this->user = $u;	  $this->pass = $p;	  $this->db = $d;	  $this->connect();	}  }  function connect($h = '', $u = '', $p = '', $d = '')  {	if ($h != '')	{	  $this->host = $h;	  $this->user = $u;	  $this->pass = $p;	  $this->db = $d;	}	$this->conn = mysql_connect($this->host, $this->user, $this->pass);	if ($this->db != '')	  mysql_select_db($this->db, $this->conn);  }  function sql($str)  {	$this->sql_stmt = $str;  }  function add_param($val, $escape = true)  {	if ($escape)	  $val = "'" . $this->escape($val) . "'";	if (!$this->params)	  $this->params = array();	$this->params[] = $val;  }  function select($limit = 0, $page = 0)  {	$this->check_db();	if ($this->sql_stmt == '')	  die ('Statement not set');	if (is_array($this->params) && count($this->params))	{	  $this->sql_stmt = vsprintf($this->sql_stmt, $this->params);	  $this->params = false;	}	if ($limit)	{	  $this->sql_stmt .= ' LIMIT ';	  if ($page)		$this->sql_stmt .= (($page - 1) * $limit) . ',';	  $this->sql_stmt .= $limit;	}	$this->result = mysql_query($this->sql_stmt);	$this->rowset = array();	while ($row = mysql_fetch_assoc($this->result))	  $this->rowset[] = $row;	mysql_free_result($this->result);	return $this->rowset;  }  function delete($limit = 0)  {	$this->check_db();	if ($this->sql_stmt == '')	  die ('Statement not set');	if (is_array($this->params) && count($this->params))	{	  $this->sql_stmt = vsprintf($this->sql_stmt, $this->params);	  $this->params = false;	}	if ($limit)	  $this->sql_stmt .= " LIMIT {$limit}";	return @mysql_query($this->sql_stmt);  }  function insert($table, $params)  {	$this->check_db();	if (!is_array($params) || count($params) == 0)	  return false;	$names = '';	$values = '';	foreach ($params as $k => $v)	{	  $names .= "{$k},";	  $values .= "'" . $this->escape($v) . "',";	}	$names = substr($names, 0, -1);	$values = substr($values, 0, -1);	return @mysql_query("INSERT INTO {$table} ({$names}) VALUES ({$values})", $this->conn);  }  function update($table, $params, $where = '')  {	$this->check_db();	if (!is_array($params) || count($params) == 0)	  return false;	$cols = '';	foreach ($params as $k => $v)	  $cols .= "{$k}={$v},";	$cols = substr($cols, 0, -1);	if ($where != '')	  $where = " WHERE {$where}";	$sql = "UPDATE {$table} SET {$cols} {$where}";	return @mysql_query($sql, $this->conn);  }  function escape($str)  {	if (get_magic_quotes_gpc())	  $str = stripslashes($str);	return mysql_real_escape_string($str, $this->conn);  }  function insert_id()  {	return mysql_insert_id($this->conn);  }  function num_rows($sql)  {	return mysql_num_rows(mysql_query($sql, $this->conn));  }  function check_db()  {	if ($this->conn == false)	  die('Database not initialized');  }  function error()  {	return 'Database Error #' . mysql_errno($this->conn) . ': ' . mysql_error($this->conn);  }}?>

I called those files class.session.php and class.db.php. I have a file called global.config.php that includes some config info:

<?php$config = array(  'db_host' => 'localhost',  'db_user' => 'root',  'db_pass' => 'password',  'db_name' => 'db_name');?>

And then I have a file called global.init.php that includes everything else:

<?phpif (version_compare('5', PHP_VERSION, '>')){  echo 'This application requires PHP version 5 or later.';  exit();}require_once 'global.config.php';require_once 'class.db.php';$db = new tc_lms_database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);require_once 'class.session.php';$sess = new tc_lms_session();?>

So including the global.init.php file on any page creates objects called $db and $sess. The session class will automatically start the session and see if there is any information in it. If so, it will populate all of the fields again (user ID, username, fullname, etc). To log a user in you can use the login method of that class. This is literally all the code I use to log in a user:

$response['success'] = $sess->login($_POST['username'], sha1($_POST['password']));if (!$response['success'])  $response['errors'][] = array('id' => $sess->error_field, 'msg' => $sess->error);

I'm using this with the Ext framework, so I build a response array to send back to Javascript. But you could do anything. I use $sess->login and send the username and password, and it returns true or false if the user successfully logged in. If it returns false, then the $sess->error property contains the error message and the $sess->error_field property contains the field that caused the error (username, password, etc). To check if someone is logged in on any page you can check if $_SESSION['userid'] > 0. If so, then they are logged in. To check if they are an admin you can check $sess->main_admin. To check any other user field (like last IP address), you can check $sess->userdata['last_ip'], or whatever the database field is called. To log a user out you just call $sess->logout() and it destroys the session.This is my users table in the database:

CREATE TABLE `users` (  `id` int(11) NOT NULL auto_increment,  `username` varchar(50) collate utf8_unicode_ci NOT NULL,  `password` varchar(40) collate utf8_unicode_ci NOT NULL,  `fname` varchar(255) collate utf8_unicode_ci default NULL,  `lname` varchar(255) collate utf8_unicode_ci default NULL,  `email` varchar(255) collate utf8_unicode_ci default NULL,  `active` tinyint(1) NOT NULL,  `date_registered` int(11) NOT NULL,  `last_login` int(11) NOT NULL,  `last_ip` varchar(15) collate utf8_unicode_ci default NULL,  `main_admin` tinyint(1) NOT NULL,  PRIMARY KEY  (`id`),  KEY `username` (`username`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The database class is pretty easy to use. With things like insert and update, you create an associative array of fields and then tell it which table to use. It will take care of escaping quotes for you. So this is how you insert a new user:

$insert = array();$insert['username'] = form_var('username');$insert['email'] = form_var('email');$insert['fname'] = form_var('fname');$insert['lname'] = form_var('lname');$password = form_var('password');$insert['password'] = sha1($password);$insert['active'] = 1;$insert['date_registered'] = time();$db->insert('users', $insert);

This is how you would update a user who wants to change their first and last name:

$update = array();$update['fname'] = form_var('fname');$update['lname'] = form_var('lname');$db->update('users', $update, 'id=' . intval(form_var('userid')));

So you send the update method the table name, the array of values, and the where clause (where id=xxx). This is the form_var function I keep using:

function form_var($var){  $retval = '';  if (isset($_POST[$var]))	$retval = trim($_POST[$var]);  elseif (isset($_GET[$var]))	$retval = trim($_GET[$var]);  if (get_magic_quotes_gpc())	$retval = stripslashes($retval);  return $retval;}

You could add that to global.init.php or something. To do a select statement, you first send the statement with all your parameters specified, then you add the parameters. You can see one example of that in the login method for the session class.

$db->sql("SELECT * FROM table WHERE field1 = %s AND field2 = %s AND field3 = %s");$db->add_param("field 1 value");$db->add_param("field 2 value");$db->add_param("value for field 3");$result = $db->select();

The return value ($result) will be a multidimensional array. If there is only one row returned, it will be in $result[0]. Otherwise you can use a for loop to loop through $result and get each row. You can use print_r($result) if you want to check the structure of it. The select method also supports paging, so if you want to show 15 items per page and you want to show page 3, you would do this:$result = $db->select(15, 3);For more information about the syntax of the string that you send to $db->sql, check the reference for sprintf:http://www.php.net/manual/en/function.sprintf.phpThe %s modifier just means that it will be a string. You don't need quotes there, the add_param method will add them if necessary. If you want to add a parameter that you don't want to escape and you don't want quoted, you can send false for the second parameter. So you would do that if you were using a number or if you had already escape and quoted the value yourself:$db->add_param($some_number, false); // don't escape the valueDelete works the same way as select, first you use $db->sql to set the SQL statement, then you call $db->delete().Take a look through everything and let me know if you have questions or problems trying to get it set up with your own application. Also, if anyone finds any problems with it or sees room for improvement please let me know as well.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...