Posted By

cdog on 03/08/11


Tagged

login php user facebook


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

HalfWinter
ApeWare
piercemoore


PHP user / facebook login class


 / Published in: PHP
 

probably confusing. it's my first class. not pretty but it works

  1. <?php
  2. /**
  3.  * User class
  4.  *
  5.  * A class to login users via username and password,
  6.  * facebook connect, or from a saved cookie.
  7.  * This is my first ever class built as a start
  8.  * to learning PHP OOP. Might not be "perfect" but
  9.  * it works.
  10.  *
  11.  * To call the class in your files do the following
  12.  * *************************************************************
  13.  * include("class.user.php");
  14.  * include("facebook.php") // need facebook PHP SDK Link below
  15.  * // http://snipplr.com/view/50300/facebook-connect-script/
  16.  * // initiate the object
  17.  * $UI = new user($fbid, $fbinfo);
  18.  
  19.  // logging someone in via form or facebook connect when they
  20.  * CLICK login. Should be on a login page
  21.  *
  22.  * $_POST['username'] = INPUT VALUE FROM A LOGIN FORM
  23.  * $_POST['password'] = INPUT VALUE FROM A LOGIN FORM
  24.  * $fbid = FACEBOOK ID FROM FACEBOOK SCRIPT
  25.  * $fbinfo = FACEBOOK INFO FROM FACEBOOK SCRIPT
  26.  * (int)$_GET['liwfb'] = used on a "fake" facebook login button when we don't log a user out of facebook
  27.  * $_POST'remember'] = form value for people that want a cookie set
  28.  *
  29.  * how to call the login method
  30.  * most likely you'll have a session started (you should have session_start() first thing on every page
  31.  * with logged in users) so cookie is set outside of the class
  32.  *
  33.  * $UI->login($_POST['username'], $_POST['password'], $fbid, $fbinfo, (int)$_GET['liwfb'], $remember);
  34. if($UI->_loggedIn) {
  35. if($_POST['remember'])
  36. {
  37. $cid = $UI->setCookie();
  38. $redurl = "link to an external page for setting the cookie.php?cid=cid checked against the database
  39. }
  40.  * *************************************************************
  41.  * @author Clint Chaney <[email protected]>
  42.  * @copyright 2011 ONIT Industries
  43.  * @license http://www.php.net/license/3_01.txt PHP License 3.01
  44.  * This program is free software: you can redistribute it and/or modify
  45.   it under the terms of the GNU General Public License as published by
  46.   the Free Software Foundation, either version 3 of the License, or
  47.   (at your option) any later version.
  48.  
  49.   This program is distributed in the hope that it will be useful,
  50.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  51.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  52.   GNU General Public License for more details.
  53.  */
  54. class user
  55. {
  56. public $_info = array(); // array of user profile information
  57. public $_loggedIn = false; // true or false if user is logged in
  58. public $_loggedInFB = false; // true or false if user used facebook to login
  59. public $_errors = array(); // errors
  60.  
  61. private $_username;
  62. private $_password;
  63. private $_facebook_id;
  64. private $_facebook_info = array();
  65. private $_facebook_login = false;
  66.  
  67. /**
  68. * CONSTRUCT
  69. *
  70. * Aaccepts facebook id and info
  71. */
  72. public function __construct($fbid='', $fbinfo='')
  73. {
  74. $this->_facebook_id = $fbid;
  75. $this->_facebook_info = $fbinfo;
  76. ($_COOKIE['usercook']) ? $this->login('','','','','','', $_COOKIE['usercook']) : '';
  77. $this->_loggedIn = ($_SESSION['uinfo']) ? true : false;
  78. $this->_info = ($this->_loggedIn) ? $_SESSION['uinfo'] : '';
  79. $this->_loggedInFB = $_SESSION['uinfo']['loggedInFB'];
  80. }
  81.  
  82.  
  83. /**
  84. * login mehod
  85. *
  86. * this should be called on a login page
  87. * as explained above.
  88. *
  89. */
  90. public function login($username='', $password='', $facebook_id='', $facebook_info='', $liwfb=false, $remember = false, $cookie = false)
  91. {
  92. $this->_username = $username;
  93. $this->_password = $password;
  94. $this->_facebook_id = $facebook_id;
  95. $this->_facebook_info = $facebook_info;
  96. $this->_facebook_login = $liwfb;
  97.  
  98. // check to see if there is a session already, if not execute a login
  99. if(!$_SESSION['uinfo'])
  100. {
  101. // if the user has a cookie verify and log them in with it
  102. if($cookie)
  103. {
  104. // check the database cookie information
  105. $check = $this->getDBInfo('cookie');
  106.  
  107. // if the check returns an active member
  108. if($check['mem_id'] && $check['mem_active'])
  109. {
  110. // register the session
  111. $this->sessionRegister($check);
  112. // make sure to let the script know were not using facebook
  113. $this->_loggedInFB = false;
  114. // do updates to the member database
  115. mysql_query("UPDATE members SET mem_last_active = '".time()."' WHERE mem_id = '".$check['mem_id']."' LIMIT 1");
  116. }
  117. // if we have a facebook id and no username and password it's a facebook login
  118. } elseif($this->_facebook_id && !$this->_username && !$this->_password)
  119. {
  120. // check to see if user is already registered
  121. $check = $this->getDBInfo('facebook');
  122. // if they are lets log them in
  123. if($check['mem_id'])
  124. {
  125. // if they haven't manually logged out or hit our fake login button
  126. if(($check['mem_manual_logout'] != 1 && $this->_facebook_id && !$this->_loggedIn) || $this->_facebook_login)
  127. {
  128. // setfacebook login to true
  129. $this->_loggedInFB = true;
  130. // register session
  131. $this->sessionRegister($check);
  132. // change manul logout to 0, gets reset on logout
  133. mysql_query("UPDATE members SET mem_manual_logout = '0' WHERE mem_id = '".$check['mem_id']."' LIMIT 1");
  134. }
  135. // they are not a member yet? let's register them
  136. } else {
  137.  
  138. // register facebook user into the database
  139. $this->registerFB();
  140. // get info from the database, most importantly their new member id
  141. $check = $this->getDBInfo('facebook');
  142. // set facebook login as true
  143. $this->_loggedInFB = true;
  144. // register our own sessioon for the user
  145. $this->sessionRegister($check);
  146.  
  147. }
  148.  
  149. // if they entered a username and password lets check it and log them in
  150. } elseif($this->_username && $this->_password)
  151. {
  152. // person is entering a username and password lets check it against the database
  153. $check = $this->getDBInfo('unp');
  154.  
  155. // if there is an id for the user let's set the session up
  156. if($check['mem_id'] && $check['mem_active'])
  157. {
  158. // set session variables
  159. $this->sessionRegister($check);
  160. // not logged in through facebook
  161. $this->_loggedInFB = false;
  162. // update lsst acivity date, probably might be a good idea to make a method for this. oh well
  163. mysql_query("UPDATE members SET mem_last_active = '".time()."' WHERE mem_id = '".$check['mem_id']."' LIMIT 1");
  164.  
  165. } else {
  166. // bad username and password, set error
  167. $this->_errors[] = "Invalid username and password.";
  168.  
  169. }
  170. }
  171. // return the session info
  172. return $this->_info;
  173.  
  174. // we already have a session. lets check the facebook info on it and return the session
  175. } else {
  176.  
  177. $this->_loggedInFB = $_SESSION['uinfo']['loggedInFB'];
  178. return $_SESSION['uinfo'];
  179. }
  180. }
  181.  
  182.  
  183. /**
  184. * register a new facebook user
  185. *
  186. * either adds a new member or
  187. * checks for an existing member with same email
  188. * and updates it.
  189. *
  190. */
  191. private function registerFB()
  192. {
  193. $fbinfo = $this->_facebook_info;
  194. // lets get location information from facebook. city and state
  195. $location = explode(',', $fbinfo['location']['name']);
  196. $city = addslashes(trim($location[0]));
  197. $state = addslashes(trim(substr($location[1], 0, 3)));
  198. // check database for zipcode information
  199. $zipinfo = mysql_fetch_array(mysql_query("SELECT * FROM zip_code WHERE city = '".$city."' && state = '".$state."' LIMIT 1"));
  200. // see if email already exists
  201. $checku = mysql_fetch_array(mysql_query("SELECT mem_id FROM members WHERE mem_email = '".filter_var($fbinfo['email'], FILTER_SANITIZE_EMAIL)."' LIMIT 1"));
  202.  
  203. if(!$checku['mem_id'])
  204. {
  205. // facebok user not in the database, add them
  206. mysql_query("INSERT INTO members SET
  207. mem_email = '".filter_var($fbinfo['email'], FILTER_SANITIZE_EMAIL)."',
  208. mem_real = '1',
  209. mem_ip = '".$_SERVER['REMOTE_ADDR']."',
  210. mem_date_joined = '".time()."',
  211. mem_last_active = '".time()."',
  212. mem_firstname = '".$this->clean($fbinfo['first_name'])."',
  213. mem_lastname = '".$this->clean($fbinfo['last_name'])."',
  214. mem_city = '".$zipinfo['city']."',
  215. mem_state = '".$zipinfo['state']."',
  216. mem_zipcode = '".$zipinfo['zip_code']."',
  217. mem_lat = '".$zipinfo['lat']."',
  218. mem_lon = '".$zipinfo['lon']."',
  219. mem_gender = '".$this->clean($fbinfo['gender'])."',
  220. mem_timezone = '".$this->clean($fbinfo['timezone'])."',
  221. mem_oauth_provider = 'facebook',
  222. mem_oauth_uid = '".$this->_facebook_id."'");
  223. } else {
  224. mysql_query("UPDATE members SET
  225. mem_last_active = '".time()."',
  226. mem_firstname = '".$this->clean($fbinfo['first_name'])."',
  227. mem_lastname = '".$this->clean($fbinfo['last_name'])."',
  228. mem_city = '".$zipinfo['city']."',
  229. mem_state = '".$zipinfo['state']."',
  230. mem_zipcode = '".$zipinfo['zip_code']."',
  231. mem_lat = '".$zipinfo['lat']."',
  232. mem_lon = '".$zipinfo['lon']."',
  233. mem_oauth_provider = 'facebook',
  234. mem_oauth_uid = '".$this->_facebook_id."'
  235. WHERE mem_id = '".$checku['mem_id']."' LIMIT 1");
  236. }
  237.  
  238. }
  239.  
  240. /**
  241. * generate a random cookie id
  242. *
  243. * generates a cookie id and ads it to the database
  244. */
  245. function setCookie()
  246. {
  247.  
  248. $cookie = $this->create_pcookie(50);
  249. mysql_query("UPDATE members SET mem_cookie_id = '".$cookie."' WHERE mem_id = '".$this->_info['id']."' LIMIT 1");
  250. return $cookie;
  251.  
  252. }
  253.  
  254.  
  255. /**
  256.   * logout a user
  257.   *
  258.   * destroy cookie on a seoerate page without session_start
  259.   *
  260.   */
  261. public function logout()
  262. {
  263. mysql_query("UPDATE members SET mem_manual_logout = '1' WHERE mem_id = '".$this->_info['id']."' LIMIT 1");
  264. $this->_loggedIn = false;
  265. $this->_loggedInFB = false;
  266. }
  267.  
  268.  
  269. /**
  270.   * register a session for a successful login
  271.   *
  272.   */
  273. private function sessionRegister($memberArray)
  274. {
  275. $this->_info = $_SESSION['uinfo'] = array(
  276. 'id' => $memberArray['mem_id'],
  277. 'email' => $memberArray['mem_email'],
  278. 'username' => $memberArray['mem_nick'],
  279. 'active' => $memberArray['mem_active'],
  280. 'level' => $memberArray['mem_level'],
  281. 'facebook_id' => $memberArray['mem_oauth_uid'],
  282. 'loggedInFB' => $this->_loggedInFB
  283. );
  284.  
  285. $this->_loggedIn = true;
  286.  
  287. }
  288.  
  289. /**
  290.   * checks for different login methods
  291.   *
  292.   */
  293. public function getDBInfo($method)
  294. {
  295. if($method == 'facebook')
  296. {
  297. return mysql_fetch_array(mysql_query("SELECT * FROM members WHERE mem_oauth_provider = 'facebook' && mem_oauth_uid = '".$this->_facebook_id."' LIMIT 1"));
  298.  
  299. } elseif($method == 'unp') {
  300.  
  301. $cleanUsername = $this->clean($this->_username);
  302. $cleanPassword = md5($this->_password);
  303. return mysql_fetch_array(mysql_query("SELECT * FROM members WHERE mem_nick = '".$cleanUsername."' && mem_password = '".$cleanPassword."' LIMIT 1"));
  304.  
  305. } elseif($method == 'email') {
  306.  
  307. $cleanUsername = $this->clean($this->_username);
  308. return mysql_fetch_array(mysql_query("SELECT * FROM members WHERE mem_nick = '".$cleanUsername."' && mem_password = '".$cleanPassword."' LIMIT 1"));
  309.  
  310. } elseif($method == 'cookie') {
  311.  
  312. // cookie string has user_id| added to the beginning of it so split it up
  313. $cookieArr = explode("|", $_COOKIE['usercook']);
  314. $cmem = (int)$cookieArr[0];
  315. $ccid = $cookieArr[1];
  316. return mysql_fetch_array(mysql_query("SELECT * FROM members WHERE mem_id = '".$cmem."' && mem_cookie_id = '".$this->clean($ccid)."' LIMIT 1"));
  317.  
  318. } else {
  319.  
  320. return false;
  321.  
  322. }
  323. }
  324.  
  325. /**
  326. *
  327. *
  328. * method to clean information for the database
  329. *
  330. *
  331. */
  332. private function clean($textToClean)
  333. {
  334. return addslashes(filter_var($textToClean, FILTER_SANITIZE_STRING));
  335. }
  336.  
  337. /**
  338. * display erros if requested
  339. **/
  340. public function showErrors()
  341. {
  342. for($i=0; $i<count($this->_errors); $i++)
  343. {
  344. print ($this->_errors[$i].'<br />');
  345. }
  346. }
  347.  
  348. /**
  349. * get a users information
  350. **/
  351. public function getInfo($id)
  352. {
  353. $info = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE mem_id = ".$id." LIMIT 1"));
  354. return $info;
  355. }
  356.  
  357. /**
  358. * method for member only psages
  359. */
  360. public function requireLogin()
  361. {
  362. if(!$this->_info['id'])
  363. {
  364. echo '<div class="fullWidth">'.
  365. '<h1>You must be logged in to view this page</h1><hr />';
  366. include('includes/forms/login.php');
  367. echo '<div class="clear"></div>'.
  368. '</div>';
  369. exit();
  370. }
  371. }
  372.  
  373. // random cookie generator
  374. function create_cookie($length=8) {
  375. #creates random 8-char alphanumeric password
  376.  
  377. $length=$length;
  378. $list=array_merge(range('a','z'),range(0,9));
  379. shuffle($list);
  380. $passwd=substr(join($list),0,$length);
  381.  
  382. return $passwd;
  383. }
  384.  
  385. }
  386.  
  387. ?>

Report this snippet  

You need to login to post a comment.