Posted By

tylerhall on 11/30/-1


Tagged

login auth class php


Versions (?)

Who likes this?

234 people have marked this snippet as a favorite

daniel
luman
College
Roshambo
andyh
luxuryluke
jamesmcoats
Fixe
jkochis
nicolaspar
px
bicherele
irdial
hxseven
olive
blakeb
Hollow
jackol
hkmd
dmarten
demods
banjomamo
frankyfish
KilgoreTrout67
tayles
olivernautsch
login
fael
vali29
hudge
willcodeforfood
hariharank12
Mithun
jfherring
skywalker
mbcdg
JimiJay
cschlens
catrinho
n00ge
SpinZ
cidibee
mb
paullorentzen
Arzakon
pixelhandler
mrjthethird
benschumacher
egoens
blackabee
pablodgavilan
tikitakfire
jsalo
crashdr
nickdoherty
sumandahal
oriolfb
atma
Shocm
latavish
canberkol
garretjames
irishsk
dharma
salibaray
iconsis
VaiT
jackii
l1r
baqc
ilumin
dzone
silverskymedia
PapTom
jstnjns
vip4lyf
scottwf
owais
willwish
kernelpanics
rezzz
nmakarov
geothen
mtelligent
grassdog
ikimozu
asdfqwer
cjwilburn
spittingangels
nb109
trdunsworth
techmaster
hasantayyar
sheedy
moussin
JustGreg
maxvee8
matiit
calvingilbert
muoto
acosonic
rene-design
KF
Gr33d
nerdfiles
Blacksnipe
novatvstdios
polarbear
profpatsy
kellyrmartin
ruhanirabin
gutierrezgcf
GandalfGrey
kkathman
wizard04
ren
Knarf
konpao
farondomenicgmailcom
webtronix
franverona
eivind
vhinsce
xuma
jaff
tapdrup
matthall
larste
khaled
harrydeluxe
leecsargent
fyreflyX
omardixon
sandynata
jschilling
beneberle
alexteg
galofre
kaartz
stevember
hsousa
silviud
dantreacy
FaustVIII
sethetter
alessio2
rasha
osirisinternet
verhaeg
siyingui
sree01
kohvihoor
iamadams
lolindirfaelivrin
FedericoBiccheddu
pytheas
pixelsoul
ahmedalttai
pchengsf
Darsain
shalomfriss
miceno
netvtech
athanassiadis
seanpowell
bobbym245
Qtronik
bindaskhan2004hotmailcom
MrFjords
lifewishes
geoffreydv
connorjackson
poet
martins
codesniper81
jirirybar
petrykowski
RvDesigns
Desoxena
basementjack
tspitzr
aegony
garthhumphreys
sjacunningham
CyKy
intothelight
svil4ok
NeekGerd
qubestream
samkamerer
lfcortes
bkgoh
hihat
desimon
mgerdt
Almorca
Gordy
onwardonward
painteddigital
asifjavedall
JustMadMike
summer_charlie
bozok
prit
tudisco
albertomori
logiq
dajocko
benediktvaldez
robertstefan
hebertialmeida
jumichot
merritt212
carcinogen75
XjSv
designspaceship
dixon
jbyerson
stur
jsamackay
mmcachran
surekin
adelino
White
webod92
rmethod
webalosarema
clac
erikgeerling
ajcarrillo
eorhed
3polars
isnafu
supupoff


Login Class


 / Published in: PHP
 

  1. class Auth
  2. {
  3. var $user_id;
  4. var $username;
  5. var $password;
  6. var $ok;
  7. var $salt = "34asdf34";
  8. var $domain = ".domain.com";
  9.  
  10. function Auth()
  11. {
  12. global $db;
  13.  
  14. $this->user_id = 0;
  15. $this->username = "Guest";
  16. $this->ok = false;
  17.  
  18. if(!$this->check_session()) $this->check_cookie();
  19.  
  20. return $this->ok;
  21. }
  22.  
  23. function check_session()
  24. {
  25. if(!empty($_SESSION['auth_username']) && !empty($_SESSION['auth_password']))
  26. return $this->check($_SESSION['auth_username'], $_SESSION['auth_password']);
  27. else
  28. return false;
  29. }
  30.  
  31. function check_cookie()
  32. {
  33. if(!empty($_COOKIE['auth_username']) && !empty($_COOKIE['auth_password']))
  34. return $this->check($_COOKIE['auth_username'], $_COOKIE['auth_password']);
  35. else
  36. return false;
  37. }
  38.  
  39. function login($username, $password)
  40. {
  41. global $db;
  42. $db->query("SELECT user_id FROM users WHERE username = '$username' AND password = '$password'");
  43. if(mysql_num_rows($db->result) == 1)
  44. {
  45. $this->user_id = mysql_result($db->result, 0, 0);
  46. $this->username = $username;
  47. $this->ok = true;
  48.  
  49. $_SESSION['auth_username'] = $username;
  50. $_SESSION['auth_password'] = md5($password . $this->salt);
  51. setcookie("auth_username", $username, time()+60*60*24*30, "/", $this->domain);
  52. setcookie("auth_password", md5($password . $this->salt), time()+60*60*24*30, "/", $this->domain);
  53.  
  54. return true;
  55. }
  56. return false;
  57. }
  58.  
  59. function check($username, $password)
  60. {
  61. global $db;
  62. $db->query("SELECT user_id, password FROM users WHERE username = '$username'");
  63. if(mysql_num_rows($db->result) == 1)
  64. {
  65. $db_password = mysql_result($db->result, 0, 1);
  66. if(md5($db_password . $this->salt) == $password)
  67. {
  68. $this->user_id = mysql_result($db->result, 0, 0);
  69. $this->username = $username;
  70. $this->ok = true;
  71. return true;
  72. }
  73. }
  74. return false;
  75. }
  76.  
  77. function logout()
  78. {
  79. $this->user_id = 0;
  80. $this->username = "Guest";
  81. $this->ok = false;
  82.  
  83. $_SESSION['auth_username'] = "";
  84. $_SESSION['auth_password'] = "";
  85.  
  86. setcookie("auth_username", "", time() - 3600, "/", $this->domain);
  87. setcookie("auth_password", "", time() - 3600, "/", $this->domain);
  88. }
  89.  
  90. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: IanLewis on May 19, 2007

Unfortunately if you call the login or check functions without first escaping the username and password you could fall victim to SQL injection. You should make sure you escape those strings before placing them in a SQL query.

Also, whoever uses this class will need to implement the database class that you are using. Is that included somewhere on Snipplr?

Posted By: llbbl on May 27, 2007

check out :

http://phpmylogon.sourceforge.net/

It is way better than this code.

Posted By: the_coder on February 18, 2008

I don't know if it is a good idea to store(even the md5hash) the password in the cookie! It would be better if you'd store a newly generated fakesessionid in the database and the cookie.

Posted By: MMDeveloper on February 27, 2009

yeah the password should only be used during login and not carried around, there's just no need to.

Posted By: asdfqwer on May 19, 2009

Password hashing and input sanctifying aside, great job mate! Now if only more people writing PHP would follow suit and started building more modular web-applications, well then maybe other developers will start taking us seriously! :D

Posted By: maietta on July 31, 2010

I agree with lanLewis (May 19, 2007), the_coder (February 18 2008), and MMDeveloper (February 27, 2009.

Every once in a while i come across a "login" script or class for PHP that hints the prospect of being a complete solution. Each time i look through the code i realize the same practices are still being applied, and i wonder just how many sites i registered with and sign in to that may have my personal information stored in some SQL backend.... that use weakly constructed scripts or classes like this one. gringe

That was one of the driving forces behind my eventual development of Commnetivity. The php framework is about a year in development (full time) it's login system was developed from the ground up keeping in mind that not every website will use the typical username/password or email/password credential scheme, and since SSL certificates and hosting with dedicated IP's are now available dirt cheap. (One SSL cert allowed per 1 IP in most hosting environments), the software also forces SSL where applicable. I would love to release the source code for the software... but i also have to feed myself. So instead, i offer a bit of advice to beginner programmers and even the advanced programmers alike:

PHP is a great language if you can call upon your experience in old-school website CGI development. (Perl, Python... and going way back... compiled BIN scripts.. yes... that's where cgi-bin comes from :) ) If you dont have experience, then i would highly suggest you learn about RFC standards (http://www.ietf.org/ and http://www.rfc-editor.org/rfcxx00.html are good places to start) and also look into using flowcharting as a powerful way to understand what is going on in your scripts. A lot of times coders will write scripts without a plan.. generally a failure to plan can be a failure of security or performance.

Also, look into writing in the OOP (object oriented programming) method. I'm not perfect, i still find myself in the MySQL forums looking for answers or hints to solutions, but i have taken the time to understand the naming conventions of the language.

For advanced programmers, it would be wise to realize that any language has its strong points. Perl, Python and PHP are probably the best languages for system administrators, website developers and for windows hosting environments as well. However, the majority of website "developers" or webmasters out there are scripting in PHP.. and as you might be aware, PHP allows for scripting in ways that is not only an eyesore, but a source of headaches when browsing through these user created scripts. I would highly recommend that the practice of embedding XHTML and PHP into one document be extremely limited unless the website owner enjoys expending time and money on future website development. This also leads me to to my next thought:

The reason Commnetivity was developed in PHP was for that simple reason mentioned herein: That php allows for embedded scripting XHTML in a "natural" fashion. (Commnetivity forces users to write clean, simple but powerful scripts) Unfortunately, embedded scripting has many little drawbacks including some bigger drawbacks. We humans have a lot of memory to work with.. however.. most of us think using a little bit of it at a time. It'd be best that we dont stare at a bunch of nonsense to see the bigger picture....the bigger picture being the actual logic and architecture of our scripts. We ignore that, and we have security and performance issues. A really well designed website starts with a platform that can let the website stay fast, secure, scalable and adapt rapidly to an ever evolving business model (fixed business models work well, for some, but not for majority nowadays). By adopting to PHP for this project i did myself a favor and stopped hating PHP and started hating those who contribute bad code (they KNOW others will run with it... ), and i also am hitting a market of those out there who just want to get their websites up with an easy to use, but powerful framework that lets them focus not on "learning" a new system.. but instead on the simple logistics of their projects. (The only rules are that they write clean code. Commnetivity will clean up the code and run a clean version until a new copy of the garbage code is detected.. then clean it again and run the clean copy... until a new copy of the garbage code is detected... then cleans it again and runs the clean copy.... until ... you get the point. )

Thank you for taking the time to read my rant. :)

Posted By: Qtronik on October 7, 2010

Wow this is the first time ever I read about a clear mind objective of coding theories. Even if I'm reading multiple and thousand point of view on the subject for me; a starter programmer without school learning.

Excuse my poor English !

Posted By: housecor on October 26, 2010

This snippet is rubbish. Queries are vulnerable to SQL Injection since they're not parameterized. Use of curly braces is inconsistent reducing readability. Username and password are being stored on the client-side in a cookie which adds no value, is insecure, and is totally unnecessary with the use of session. The author shows a fundamental misunderstanding of the power of session - A simple session var tracking user status on the server side would suffice and avoid the security issues of storing credentials on the client side.

Posted By: Sverri on January 2, 2011

The cookie should only contain a unique ID that cannot be predictably replicated, and nothing more. Everything else can and should be safely stored on the server. You loose control if you just leave stuff like hashes floating around in people's browsers.

Generating a random salt for every new password is also a good idea.

Posted By: wastral on January 26, 2011

It never ceases to amaze me on how many people LOVE to rip on other peoples code and not post THEIR BETTER solution. Hey "housecor " if you have all the answers and better code then why don't you post it here? I didn't write this code and I am also just learning. This code has been here since May 19, 2007 and around 8 people who ripped on it, and to my knowledge, without posting their better solution.... SHAME head shake SHAME....

Posted By: mladoux on April 21, 2012

he's using php's built in mysql or mysqli class with the current setup, so there's no need to re-implement his database class, unless you're running a version of php that does not have those builtins.

Posted By: djangofan on December 13, 2012

This code isn't much use without a good example of how its properly implemented.

Posted By: supupoff on May 25, 2014

Thanks for this code, how can i do a insert a user in database with the md5

You need to login to post a comment.