943,186 Members | Top Members by Rank

Ad:
  • PHP Code Snippet
  • Views: 30244
  • PHP RSS
0

PHP Session Management & Password Protect class

by on Jun 18th, 2005
class_session.php is a session management and password protection class. It can be used to perform 2 major functions:

1. Create and maintain session state between page hits. The class does this using simple session cache files into which the session is stored as a serialized array. This is similar to how PHP's built-in sessions store session data. One big advantage of this class is that you have full control over the session timeout.

2. Password protect PHP pages by requiring authentication. Simply pass in "true" when creating a new session object to use this functionality. You'll also need to create your own login.php script. A sample login.php is packaged with this class.

Most current information and documentation and downloads found at
http://www.troywolf.com/articles/php/class_session.

There are two complete PHP files listed below. First is the class file, class_session.php. The second is example.php to show you how to use the class.

Troy Wolf operates ShinySolutions Webhosting, and is the author of SnippetEdit--a PHP application providing browser-based website editing that even non-technical people can use. "Website editing as easy as it gets." Troy has been a professional Internet and database application developer for over 10 years. He has many years' experience with ASP, VBScript, PHP, Javascript, DHTML, CSS, SQL, and XML on Windows and Linux platforms.
PHP Code Snippet (Toggle Plain Text)
  1. class_session.php
  2. ======================================================
  3. <?php
  4. /*
  5. * Filename.......: class_session.php
  6. * Author.........: Troy Wolf [troy@troywolf.com]
  7. * Last Modified..: Date: 2005/06/18 14:20:00
  8. * Description....: A session management and password protection class.
  9.   This class can be used to perform 2 major functinos:
  10.   1. Create and maintain session state between page hits.
  11.   This class does this using simple session cache files
  12.   into which the session is stored as a serialized array.
  13.   This is similar to how PHP's built-in sessions store
  14.   session data. One big advantage of this class is that
  15.   you have full control over the session time-out.
  16.   2. Password protect PHP pages by requiring authentication.
  17.   Simply pass in "true" when creating a new session
  18.   object to use this functionality. You'll also need to
  19.   create your own login.php script. A sample login.php
  20.   is packaged with this class.
  21.  
  22.   Be sure you look at the cleanAll() method in this class.
  23. */
  24. class session {
  25.  
  26. var $id;
  27. var $data;
  28. var $log;
  29. var $dir;
  30. var $filename;
  31. var $login_page;
  32.  
  33. /*
  34.   The class constructor.
  35.   */
  36. function session($login_required=false) {
  37. $this->log = "session() called<br />";
  38. $ret = true;
  39.  
  40. /*
  41.   All the session variables are available in the data[] array. Unless you
  42.   know what you are doing, Do not use these array keys as they are used
  43.   internally by the class:
  44.   logged_in
  45.   page_destination
  46.   */
  47. $this->data = array();
  48.  
  49. /*
  50.   If you will have some pages that require login, set your login page here.
  51.   Defaults to login.php in current dir.
  52.   */
  53. $this->login_page = "login.php";
  54.  
  55. /*
  56.   Define the directory to save session files in. This defaults to the current
  57.   dir, but this is probably not what you want. For one thing, it is INSECURE!
  58.   It also will prevent your sessions from working between scripts in different
  59.   dirs. It is highly recommended that you set this to a non web-accessible
  60.   dir. End this value with a "/".
  61.   */
  62. $this->dir = realpath("./")."/";
  63.  
  64. if ($this->exists()) {
  65. $this->log .= "sid: ".$this->id."<br />";
  66. if (!$this->load()) {
  67. /*
  68.   This is not necessarily a show-stopper. This will happen if you've
  69.   previously started a session, but never saved it. This would also occur
  70.   if you delete the session's cache file during a live session.
  71.   */
  72. $this->log .= "Could not restore session.<br />";
  73. $ret = true;
  74. }
  75. } else {
  76. if (!$this->newId()) {
  77. $this->log .= "Could not create new session.<br />";
  78. $ret = false;
  79. }
  80. $this->log .= "sid: ".$this->id."<br />";
  81. }
  82.  
  83. if ($login_required) {
  84. $this->log .= "Require login requested<br />";
  85. if (!$this->data['logged_in']) {
  86. $this->log .= "Not logged in, redirecting to "
  87. .$this->login_page."<br />";
  88. $this->data['page_destination'] = $_SERVER['SCRIPT_NAME'];
  89. $this->save();
  90. header("Location: ".$this->login_page);
  91. }
  92. }
  93. return $ret;
  94. }
  95.  
  96. /*
  97.   expire() is useful for a logout feature. It will empty the session data,
  98.   delete the session file, and expire the sid cookie.
  99.   */
  100. function expire() {
  101. $this->log .= "expire() called<br />";
  102. $ret = true;
  103. $this->data = array();
  104. if (!file_exists($this->filename)) {
  105. $this->log .= $this->filename." does not exist.<br />";
  106. $ret = false;
  107. } else {
  108. if (!@unlink($this->filename)) {
  109. $this->log .= "session file delete failed for "
  110. .$this->filename."<br />";
  111. $ret = false;
  112. }
  113. }
  114. if (!setcookie('sid' ,$this->id, time()-3600, "/")) {
  115. $this->log .= "sid cookie expire failed. This may be due to browser"
  116. ." output started prior.<br />";
  117. $ret = false;
  118. }
  119. return $ret;
  120. }
  121.  
  122. /*
  123.   exists() checks if sid cookie exists on user's computer. If so, set id.
  124.   */
  125. function exists() {
  126. $this->log .= "exists() called<br />";
  127. if (!isset($_COOKIE['sid'])) {
  128. $this->log .= "sid cookie does not exist.<br />";
  129. return false;
  130. }
  131. $this->id = $_COOKIE['sid'];
  132. $this->filename = $this->dir."sid_".$this->id;
  133. return true;
  134. }
  135.  
  136. /*
  137.   newId() generates a 32 character identifier that is extremely difficult to
  138.   predict. Save to a cookie to persist between pages.
  139.   */
  140. function newId() {
  141. $this->log .= "newId() called<br />";
  142. $this->id = md5(uniqid(rand(), true));
  143. $this->filename = $this->dir."sid_".$this->id;
  144. if (!setcookie('sid' ,$this->id, null, "/")) {
  145. $this->log .= "sid cookie save failed. This may be due to browser"
  146. ." output started prior or the user has disabled cookies.<br />";
  147. return false;
  148. }
  149. return true;
  150. }
  151.  
  152. /*
  153.   load() reads in session data stored in session file.
  154.   */
  155. function load() {
  156. $this->log .= "load() called<br />";
  157. if (!file_exists($this->filename)) {
  158. $this->log .= $this->filename." does not exist.<br />";
  159. return false;
  160. }
  161. if (!$x = @file_get_contents($this->filename)) {
  162. $this->log .= "Could not read ".$this->filename."<br />";
  163. return false;
  164. }
  165. if (!$this->data = unserialize($x)) {
  166. $this->log .= "unserialize failed<br />";
  167. $this->data = array();
  168. return false;
  169. }
  170. return true;
  171. }
  172.  
  173. /*
  174.   save() stores session data in session file to persist data between pages.
  175.   */
  176. function save() {
  177. $this->log .= "save() called<br />";
  178. if (count($this->data) < 1) {
  179. $this->log .= "Nothing to save.<br />";
  180. return false;
  181. }
  182. //create file pointer
  183. if (!$fp=@fopen($this->filename,"w")) {
  184. $this->log .= "Could not create or open ".$this->filename."<br />";
  185. return false;
  186. }
  187. //write to file
  188. if (!@fwrite($fp,serialize($this->data))) {
  189. $this->log .= "Could not write to ".$this->filename."<br />";
  190. fclose($fp);
  191. return false;
  192. }
  193. //close file pointer
  194. fclose($fp);
  195. return true;
  196. }
  197.  
  198. /*
  199.   cleanAll() will clean up your session dir removing all 'sid_' files with a
  200.   modified date older than the number of minutes passed in. This method is here
  201.   as a convenience. You probably want to create a cron job that cleans this up
  202.   on a daily basis.
  203.   */
  204. function cleanAll($minutes) {
  205. $this->log .= "cleanAll() called to delete sessions older than "
  206. .$minutes." minutes<br />";
  207. chdir($this->dir);
  208. $ret = shell_exec("find -type f -name 'sid_*' -maxdepth 1 -mmin +".$minutes." -exec rm -f {} \;");
  209. }
  210.  
  211. }
  212.  
  213. ?>
  214.  
  215. example.php
  216. ======================================================
  217. <?php
  218. /*
  219. * example.php
  220. * class_session.php example usage
  221. * Author: Troy Wolf (troy@troywolf.com)
  222. */
  223.  
  224. /*
  225. Include the session class. Modify path according to where you put the class
  226. file.
  227. */
  228. require_once(dirname(__FILE__).'/class_session.php');
  229.  
  230. /*
  231. Instantiate a new session object. If session exists, it will be restored,
  232. otherwise, a new session will be created--placing a sid cookie on the user's
  233. computer. You can pass "true" to session() to require the user to login before
  234. accessing this page. Read the help documentation and the comments in
  235. class_session.php for more help with the password-protect feature.
  236. */
  237. if (!$s = new session()) {
  238. /*
  239.   There is a problem with the session! The class has a 'log' property that
  240.   contains a log of events. This log is useful for testing and debugging.
  241.   */
  242. echo "<h2>There is a problem with the session!</h2>";
  243. echo $s->log;
  244. exit();
  245. }
  246.  
  247. /*
  248. Add some data to the session.
  249. */
  250. $s->data['uname'] = "John Doe";
  251. $s->data['favcolor'] = "orange";
  252. $s->data['ip_address'] = $_SERVER['REMOTE_ADDR'];
  253.  
  254. /*
  255. Save the session.
  256. */
  257. if (!$s->save()) {
  258. /*
  259.   There is a problem with the session! The class has a 'log' property that
  260.   contains a log of events. This log is useful for testing and debugging.
  261.   */
  262. echo "<h2>There is a problem with the session!</h2>";
  263. echo $s->log;
  264. exit();
  265. }
  266.  
  267. /*
  268. On additional pages, you instantiate the session same as above. You can then
  269. access the session data using the data[] property.
  270. */
  271. echo "<br />Your name is ".$s->data['uname'];
  272. echo "<br />Your favorite color is ".$s->data['favcolor'];
  273. echo "<br />Your IP Address is ".$s->data['ip_address'];
  274.  
  275. /*
  276. Just for fun, display the session log.
  277. */
  278. echo "<hr /><b>Session log</b><br />";
  279. echo $s->log;
  280. ?>
  281.  
  282.  
Message:
Previous Thread in PHP Forum Timeline: Need help with existing code
Next Thread in PHP Forum Timeline: Need Help Creating an ad to hire a programmer for DBs





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC