So I am dealing with merging in functionality for rehashing to upgrade users to have bcrypt passwords, into a existing class I found and have set up quite successfully, its wonderful.
However, this class lacks rehashing check, which is terrible for legacy passwords on existing user databases. We need to handle SHA1 passwords! We use SHA1 + Salt, so I hope this is possible to convert.
Im using this class found here:
https://alexwebdevelop.com/user-authentication/
So using this class, I have added the following public function:
public function authenticate($username, $password)
{
/* Global $pdo object */
global $pdo;
// Database lookup
$stmt = $pdo->prepare("SELECT id, password, legacy_password FROM users WHERE username = ?");
$stmt->execute([$username]);
$stored = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$stored) {
// No such user, throw an exception
throw new Exception('Invalid user.');
}
if ($stored['legacy_password']) {
// This is the legacy password upgrade code
if (password_verify(sha1($password), $stored['password'])) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("UPDATE users SET password = ?, legacy_password = FALSE WHERE id = ?");
$stmt->execute([$newhash, $stored['id']]);
// Return the user ID (integer)
return $stored['id'];
}
} elseif (password_verify($password, $stored['password'])) {
// This is the general purpose upgrade code e.g. if a future version of PHP upgrades to Argon2
if (password_needs_rehash($stored['password'], PASSWORD_DEFAULT)) {
$newhash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->execute([$newhash, $stored['id']]);
}
// Return the user ID (integer)
return $stored['id'];
}
// When all else fails, throw an exception
throw new Exception('Rehashing failed.');
}
Now inside the login() function of the class, I have replaced
public function login($name, $passwd)
{
...
if (is_array($row)) {
if (password_verify($passwd, $row['password'])) {
/* Authentication succeeded. Set the class properties (id and name) */
$this->id = intval($row['id'], 10);
$this->name = $name;
$this->authenticated = TRUE;
/* Register the current Sessions on the database */
$this->registerLoginSession();
/* Finally, Return TRUE */
return TRUE;
}
}
}
With this:
public function login($name, $passwd)
{
...
if (is_array($row)) {
$userid = $this->authenticate($name, $row['password']);
if (password_verify($passwd, $row['password'])) {
/* Authentication succeeded. Set the class properties (id and name) */
$this->id = intval($userid);
$this->name = $name;
$this->authenticated = TRUE;
/* Register the current Sessions on the database */
$this->registerLoginSession();
/* Finally, Return TRUE */
return TRUE;
}
}
}
And so it is supposed to return the hand back the ID after check / rehashing. So it finds me as a user, as tested. Good.. so now all authenticate() does is throw exception error of failure. I can't figure out how to get error messages out of this.
This seems like this the exact thing to do with this ID, what am I doing wrong?
This point of this: User logs in with SHA1 (salted) password in form, script rehashes password, and user logs in like nothing happened.
authenticate() conversion function I'm using:
https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016#legacy-hashes
Im so sorry! I have learned from the suggestions here and I appreciate all the help!
So I solved this myself. What I did was remove authenticate() function, and instead tackled this directly based on the feedback comments (I couldn't agree more).
I replaced the last code block in the post, with this:
if (is_array($row)) {
if (password_needs_rehash($row['password'], PASSWORD_DEFAULT)) {
$newhash = password_hash($passwd, PASSWORD_BCRYPT);
$stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->execute([$newhash, $row['id']]);
}
if (password_verify($passwd, $row['password'])) {
/* Authentication succeeded. Set the class properties (id and name) */
$this->id = intval($row['id'], 10);
$this->name = $name;
$this->authenticated = TRUE;
/* Register the current Sessions on the database */
$this->registerLoginSession();
/* Finally, Return TRUE */
return TRUE;
}
}
And users passwords are rehashing, and logging in!
I'm writing an MVC style application using OO PHP and have run into an issue when trying to use different classes when trying to register/login users. Essentially, I have an abstract User class holding some common properties and functions and 2 classes which extend this: a LoginUser class created when a user attempts to login and a RegisterUser class created when a user attempts to register.
My issue is this: When I successfully add a user to my database using a query that is called in the RegisterUser class (using the password_hash function on the password) and then try to login via a query called in the LoginUser class (using the password_verify function) the query result returns false, even when the password supplied is definitely the password that was entered at registration.
My question is this: Does the password_verify function have to be called by an object of the same class that used the password_hash function to create the hash? If so, why? I have tried looking at the PHP documentation and search results do not return an answer either!
The reason that I ask this is because the registration/login will succeed if all of the functions are held in a single User class, instead of inherited classes.
My User class:
abstract class User {
protected $checkedUserName = '';
protected $checkedPassword = '';
public function __construct($uncheckedUserName, $uncheckedPassword) {
$this->checkedUserName = $this->validateAndSanitizeUserName($uncheckedUserName);
$this->checkedPassword = $this->validateAndSanitizePassword($uncheckedPassword);
}
protected function validateAndSanitizeUserName($uncheckedUserName) {
$string = filter_var($uncheckedUserName, FILTER_VALIDATE_EMAIL); // Checks input is an email
$string = filter_var($string, FILTER_SANITIZE_EMAIL); // Removes illegal chars
$string = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS); // Removes HTML tags, etc replacing them with char codes
return $string;
}
protected function validateAndSanitizePassword($uncheckedPassword) {
$string = filter_var($uncheckedPassword, FILTER_VALIDATE_REGEXP, ["options"=>["regexp"=>"/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/"]]); // Checks the password against the regex on the form
$string = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS); // Removes HTML tags, etc replacing them with char codes
return $string;
}
protected function checkIfUserExists() {
// Set the initial status of user exists
$userExists = false;
// Open a connection to the database
$con = Db::getInstance();
// Prepare the query
$checkIfUserExists = $con->prepare("SELECT * FROM users2 WHERE username=?");
//Execute the query with the checked username
$checkIfUserExists->execute([$this->checkedUserName]);
// Set $userExists dependent on result
if($checkIfUserExists->rowCount() !== 0) {
$userExists = true;
}
return $userExists;
}
}
My LoginUser class:
class LoginUser extends User{
public function __construct($uncheckedUserName, $uncheckedPassword) {
parent::__construct($uncheckedUserName, $uncheckedPassword);
}
private function getPasswordHashes() {
// Only connect to the database when connection is needed
$con = Db::getInstance();
// Check if username and password match
// Prepare the query
$checkUser = $con->prepare("SELECT * from users2 WHERE username = ?");
// Execute the query using an array to bind the parameter to ?
$checkUser->execute([$this->checkedUserName]);
return $checkUser;
}
public function getLogInResult() {
// Initialise the results variable
$resultsFound = 0;
// Only proceed if the username actually exists
if($this->checkIfUserExists()) {
// Call the function to get the records that match the username
$checkUser = $this->getPasswordHashes();
// Check to see if exactly one match was found and verify the password
if($checkUser->rowCount() === 1) { // Note this may not work in other databases - it does in MySQL
foreach($checkUser as $user) {
if(password_verify($this->checkedPassword, $user['passwordHash'])) {
$resultsFound++;
}
}
}
return $resultsFound;
}
}
}
My RegisterUser class:
lass RegisterUser extends User{
private $checkedFirstName = '';
private $checkedLastName = '';
public function __construct($uncheckedUserName, $uncheckedPassword, $uncheckedFirstName, $uncheckedLastName) {
parent::__construct($uncheckedUserName, $uncheckedLastName);
$this->checkedFirstName = $this->sanitizeString($uncheckedFirstName);
$this->checkedLastName = $this->sanitizeString($uncheckedLastName);
}
private function sanitizeString($uncheckedString) {
$string = filter_var($uncheckedString, FILTER_SANITIZE_STRING);
return $string;
}
private function insertUserDetails() {
// Hash the supplied password in preparation for insertion
//$hashedPassword = password_hash($this->checkedPassword, PASSWORD_DEFAULT);
// Connect to the database
$con = Db::getInstance();
// Prepare the query
$addUser = $con->prepare("INSERT INTO users2 VALUES (?, ?, ?, ?)");
// Execute the query using an array to bind the parameters
$addUser->execute([$this->checkedUserName, password_hash($this->checkedPassword, PASSWORD_DEFAULT), $this->checkedFirstName, $this->checkedLastName]);
// Return the result
return $addUser;
}
public function getRegisterResult() {
// Initialise the variable to store the result state
$result = false;
// Only proceed if the username does not exist
if(!($this->checkIfUserExists())) {
$addUser = $this->insertUserDetails();
// If the details were successfully added
if($addUser->rowCount() === 1) {
$result = true;
}
}
return $result;
}
}
So, when completing the registration form, the getRegisterResult() function is called on a new RegisterUser object. When logging in, the getLoginResult() function is called on a new LoginUser object but the result returns false...
In answer to my question, it doesn't matter which classes use password_hash and password_verify, if there's a match with the password to verify and the hash from the database it should return a positive result!
The issue was with __construct() for the RegisterUser class - the call to the parent passed in $uncheckedLastName rather than the $uncheckedPassword and therefore the password being set at registration was not what was supplied in the password field but that what was supplied in the LastName field!
I am developing an e-commerce website on which i need to store sessions inside database.I did that by implementing SessionHandlerInterface Class that is provided by the php itself.However it works totally fine and did store sessions inside the database , as well as read them properly.
However I am facing problem when I am using unset to unset a session variable.Sometimes it does work.Sometimes it doesn't.
For example:If i have a session variable by the name ABC unset might delete it from the database or it doesn't deletes the variable.
<?php
//inc.session.php
require_once 'RemoteAddress.php';
class SysSession implements SessionHandlerInterface
{
private $remote_write;
private $remote_read;
private $link;
private $ip_address_write;
private $ip_address_read;
public function open($savePath, $sessionName)
{
$link = new mysqli("localhost","root","","cakenbake");
if($link){
$this->link = $link;
return true;
}else{
return false;
}
}
public function close()
{
mysqli_close($this->link);
return true;
}
public function read($id)
{
$this->remote_read=new RemoteAddress();
$this->ip_address_read=$this->remote_read->getIpAddress();
$stmt=$this->link->prepare("SELECT `Session_Data`,`ip_address` FROM Session WHERE `Session_Id` = ? AND `Session_Expires` > '".date('Y-m-d H:i:s')."'");
$stmt->bind_param("s",$id);
$stmt->execute();
//$result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
/*$result=$this->link->prepare("Some query inside")
* This shows up an error stating prepare method not found
*
*/
$res=$stmt->get_result();
if($row=$res->fetch_assoc()){
if($this->ip_address_read==$row['ip_address'])
return $row['Session_Data'];
else return "";
}else{
return "";
}
}
public function write($id, $data)
{
$this->remote_write=new RemoteAddress();
$this->ip_address_write=$this->remote_write->getIpAddress();
if(!empty($data))
{
$DateTime = date('Y-m-d H:i:s');
$NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
$stmt=$this->link->prepare("REPLACE INTO Session SET Session_Id = ?, Session_Expires = '".$NewDateTime."', Session_Data = '".$data."', ip_address = '".$this->ip_address_write."'");
$stmt->bind_param("s",$id);
// $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
public function destroy($id)
{
$stmt = $this->link->prepare("DELETE FROM Session WHERE Session_Id =?");
$stmt->bind_param("s",$id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
public function gc($maxlifetime)
{
$result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < UNIX_TIMESTAMP(NOW()))");
if($result){
return true;
}else{
return false;
}
}
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>
The above code stores and read sessions from the database.
Structure of the session table.
What could be the possible reason for this weird behaviour. Do i have to implement unset function as well?.
How should i resolve this problem?
If you could suggest me someother already written code for storing in database.That would work as well but i dont need any frameworks such as codeigniter and Yii2.
If you need more information regarding this problem.I will update my question.
Thanks in advance!
The problem is not with the unset function but with your write function.The write function is responsible for any updates that are made to the specific session id.
The wierd behiviour is not with the unset but it is with the write funciton you have implemented.
See ,the !empty constraint checks if your data is empty or not.What i can guess is that your database for that specific id must be empty after the removal of the specific variable .So the write tries to update your row with an empty value but with that constraint it isn't able to do so.
Just remove the !empty tag and it will work like a charm.
Im having problems with creating a session class - Im trying to pass the database object to it to call its functions however I keep getting the error call to undefined function at like 46 of ssession.class.php, OR, as weird as this sound, gives me a diffrent error that its called on a non-object. I thought you could store objects as class variables and don't understand why its not finding database.
<?php
include("http://www.walkingspheres.com/include/database.class.php");
include("http://www.walkingspheres.com/include/mailer.php");
include("http://www.walkingspheres.com/include/form.php");
class Session
{
var $username; //Username given on sign-up
var $sessionid; //Random value generated on current login
var $userlevel; //The level to which the user pertains
var $time; //Time user was last active (page loaded)
var $logged_in; //True if user is logged in, false otherwise
var $userinfo = array(); //The array holding all user info
var $url; //The page url current being viewed
var $referrer; //Last recorded site page viewed
var $database;
/* Class constructor */
function Session($db){
$this->time = time();
$this->databse = $db;
$this->startSession();
}
/**
* startSession - Performs all the actions necessary to
* initialize this session object. Tries to determine if the
* the user has logged in already, and sets the variables
* accordingly. Also takes advantage of this page load to
* update the active visitors tables.
*/
function startSession(){
session_start(); //Tell PHP to start the session
/* Determine if user is logged in */
$this->logged_in = $this->checkLogin();
/**
* Set guest value to users not logged in, and update
* active guests table accordingly.
*/
if(!$this->logged_in){
$this->username = $_SESSION['username'] = GUEST_NAME;
$this->userlevel = GUEST_LEVEL;
$this->database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestam*/
else{
$this->database->addActiveUser($this->username, $this->time);
}
/* Remove inactive visitors from database */
$this->database->removeInactiveUsers();
$this->database->removeInactiveGuests();
/* Set referrer page */
if(isset($_SESSION['url'])){
$this->referrer = $_SESSION['url'];
}else{
$this->referrer = "/";
}
/* Set current url */
$this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
}
/**
* checkLogin - Checks if the user has already previously
* logged in, and a session with the user has already been
* established. Also checks to see if user has been remembered.
* If so, the database is queried to make sure of the user's
* authenticity. Returns true if the user has logged in.
*/
function checkLogin(){
/* Check if user has been remembered */
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
$this->username = $_SESSION['username'] = $_COOKIE['cookname'];
$this->sessionid = $_SESSION['sessionid'] = $_COOKIE['cookid'];
}
/* Username and sessionid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['sessionid']) &&
$_SESSION['username'] != GUEST_NAME){
/* Confirm that username and sessionid are valid */
if($this->database->confirmSessionID(
$_SESSION['username'],$_SESSION['sessionid'])!= 0)
{
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['sessionid']);
return false;
}
/* User is logged in, set class variables */
$this->userinfo = $this->database->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->sessionid = $this->userinfo['sessionid'];
$this->userlevel = $this->userinfo['userlevel'];
return true;
}
/* User not logged in */
else{
return false;
}
}
/**
* login - The user has submitted his username and password
* through the login form, this function checks the authenticity
* of that information in the database and creates the session.
* Effectively logging in the user if all goes well.
*/
function login($subuser, $subpass, $subremember){
$form; //The database and form object
/* Username error checking */
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0){
$form->setError($field, "* Username not entered");
}
else{
/* Check if username is not alphanumeric */
if(!preg_match("/^([0-9a-z])*$/", $subuser)){
$form->setError($field, "* Username not alphanumeric");
}
}
/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}
/* Return if form errors exist */
if($form->num_errors > 0){
return false;
}
/* Checks that username is in database and password is correct */
$subuser = stripslashes($subuser);
$result = $this->database->confirmUserPass($subuser, md5($subpass));
/* Check error codes */
if($result == 1){
$field = "user";
$form->setError($field, "* Username not found");
}
else if($result == 2){
$field = "pass";
$form->setError($field, "* Invalid password");
}
/* Return if form errors exist */
if($form->num_errors > 0){
return false;
}
/* Username and password correct, register session variables */
$this->userinfo = $this->database->getUserInfo($subuser);
$this->username = $_SESSION['username'] = $this->userinfo['username'];
$this->sessionid = $_SESSION['sessionid'] = $this->generateRandID();
$this->userlevel = $this->userinfo['userlevel'];
/* Insert sessionid into database and update active users table */
$this->database->updateUserField($this->username, "sessionid", $this->sessionid);
$this->database->addActiveUser($this->username, $this->time);
$this->database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
/**
* This is the cool part: the user has requested that we remember that
* he/she logged in, so we set two cookies. One to hold his/her username,
* and one to hold his/her random value sessionid. It expires by the time
* specified in definitions.php. Now, next time he/she comes to our site, we will
* log him/her in automatically, but only if she/he didn't log out before they left
*/
if($subremember){
setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", $this->sessionid, time()+COOKIE_EXPIRE, COOKIE_PATH);
}
/* Login completed successfully */
return true;
}
/**
* logout - Gets called when the user wants to be logged out of the
* website. It deletes any cookies that were stored on the users
* computer as a result of him wanting to be remembered, and also
* unsets session variables and demotes his user level to guest.
*/
function logout(){
/**
* Delete cookies - the time must be in the past,
* so just negate what you added when creating the
* cookie.
*/
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
}
/* Unset PHP session variables */
unset($_SESSION['username']);
unset($_SESSION['sessionid']);
unset($_SESSION['error_array']);
unset($_SESSION['value_array']);
unset($_SESSION['regsuccess']);
/* Reflect fact that user has logged out */
$this->logged_in = false;
/**
* Remove from active users table and add to
* active guests tables.
*/
$this->database->removeActiveUser($this->username);
$this->database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
/* Set user level to guest */
$this->username = GUEST_NAME;
$this->userlevel = GUEST_LEVEL;
}
/**
* register - Gets called when the user has just submitted the
* registration form. Determines if there were any errors with
* the entry fields, if so, it records the errors and returns
* 1. If no errors were found, it registers the new user and
* returns 0. Returns 2 if registration failed.
*/
function register($subuser,$subpass,$subemail,$c_pass,$c_email,$home,$bday){
global $form, $mailer; //The database, form and mailer object
/* Username error checking */
$field = "user"; //Use field name for username
$subuser=trim($subuser);
if(strlen($subuser) == 0){
$form->setError($field, "* Username not entered");
}
else{
/* Spruce up username, check length */
$subuser = stripslashes($subuser);
if(strlen($subuser) < 5){
$form->setError($field, "* Username below 5 characters");
}
else if(strlen($subuser) > 30){
$form->setError($field, "* Username above 30 characters");
}
/* Check if username is not alphanumeric */
else if(!preg_match("/^([0-9a-z])+$/", $subuser)){
$form->setError($field, "* Username not alphanumeric");
}
/* Check if username is reserved */
else if(strcasecmp($subuser, GUEST_NAME) == 0){
$form->setError($field, "* Username reserved word");
}
/* Check if username is already in use */
else if($this->database->usernameTaken($subuser)){
$form->setError($field, "* Username already in use");
}
/* Check if username is banned */
else if($this->database->usernameBanned($subuser)){
$form->setError($field, "* Username banned");
}
}
/* Password error checking */
$field = "password"; //Use field name for password
$subpass=trim($subpass);
$c_pass=trim($c_pass);
if(strlen($subpass)==0 || strlen($c_pass)==0){
$form->setError($field, "* Password not entered");
}
else{
/* Spruce up password and check length*/
if(strlen($subpass) < 4){
$form->setError($field, "* Password too short");
}
/* Check if password is not alphanumeric */
else if(!preg_match("/^([0-9a-z])+$/", $subpass)){
$form->setError($field, "* Password not alphanumeric");
}
/* Check if both passwords entered match */
else if(strcmp($subpass,$c_pass) != 0){
$form->setError($field, "* Passwords don't match");
}
}
/* Email error checking */
$field = "email"; //Use field name for email
$subemail=trim($subemail);
$c_email=trim($c_email);
if(strlen($subemail) == 0){
$form->setError($field, "* Email not entered");
}
else{
/* Check if valid email address */
$regex = "/^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
."#[a-z0-9-]+(\.[a-z0-9-]{1,})*"
."\.([a-z]{2,}){1}$/";
if(!preg_match($regex,$subemail)){
$form->setError($field, "* Email invalid");
}
else if(strcmp($subemail,$c_email)!=0){
$form->setError($field, "* Emails don't match");
}
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1;
}
/* No errors, add the new account to the db */
else{
$home=trim($home);
$bday=trim($bday);
if($this->database->addNewUser($subuser, md5($subpass),$subemail,$home,$bday)){
if(EMAIL_WELCOME){
$mailer->sendWelcome($subuser,$subemail,$subpass);
}
return 0; //New user added succesfully
}else{
return 2; //Registration attempt failed
}
}
}
/**
* editAccount - Attempts to edit the user's account information
* including the password, which it first makes sure is correct
* if entered, if so and the new password is in the right
* format, the change is made. All other fields are changed
* automatically.
*/
function editAccount($subcurpass, $subnewpass, $subemail){
global $form; //The database and form object
/* New password entered */
if($subnewpass){
/* Current Password error checking */
$field = "curpass"; //Use field name for current password
if(!$subcurpass){
$form->setError($field, "* Current Password not entered");
}
else{
/* Check if password too short or is not alphanumeric */
$subcurpass = stripslashes($subcurpass);
if(strlen($subcurpass) < 4 ||
!preg_match("/^([0-9a-z])+$/", ($subcurpass = trim($subcurpass)))){
$form->setError($field, "* Current Password incorrect");
}
/* Password entered is incorrect */
if($this->database->confirmUserPass($this->username,md5($subcurpass)) != 0){
$form->setError($field, "* Current Password incorrect");
}
}
/* New Password error checking */
$field = "newpass"; //Use field name for new password
/* Spruce up password and check length*/
$subpass = stripslashes($subnewpass);
if(strlen($subnewpass) < 4){
$form->setError($field, "* New Password too short");
}
/* Check if password is not alphanumeric */
else if(!preg_match("/^([0-9a-z])+$/", ($subnewpass = trim($subnewpass)))){
$form->setError($field, "* New Password not alphanumeric");
}
}
/* Change password attempted */
else if($subcurpass){
/* New Password error reporting */
$field = "newpass"; //Use field name for new password
$form->setError($field, "* New Password not entered");
}
/* Email error checking */
$field = "email"; //Use field name for email
if($subemail && strlen($subemail = trim($subemail)) > 0){
/* Check if valid email address */
$regex = "/^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
."#[a-z0-9-]+(\.[a-z0-9-]{1,})*"
."\.([a-z]{2,}){1}$/";
if(!preg_match($regex,$subemail)){
$form->setError($field, "* Email invalid");
}
$subemail = stripslashes($subemail);
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return false; //Errors with form
}
/* Update password since there were no errors */
if($subcurpass && $subnewpass){
$this->database->updateUserField($this->username,"password",md5($subnewpass));
}
/* Change Email */
if($subemail){
$this->database->updateUserField($this->username,"email",$subemail);
}
/* Success! */
return true;
}
/**
* isAdmin - Returns true if currently logged in user is
* an administrator, false otherwise.
*/
function isAdmin(){
return ($this->userlevel == ADMIN_LEVEL ||
$this->username == ADMIN_NAME);
}
/**
* confirmFriends - pre: sessionid, requestingid
* returns true if they are both friends
* else returns false
*/
function confirmFriends($uid,$rid){
$q = "SELECT name FROM friends WHERE userid_fk='$uid' AND fid='$rid' ";
$res->$this->database->query($q);
if($res){ //exists
return true;
}
else
return false;
}
/**
* generateRandID - Generates a string made up of randomized
* letters (lower and upper case) and digits and returns
* the md5 hash of it to be used as a sessionid.
*/
function generateRandID(){
return md5($this->generateRandStr(16));
}
/**
* generateRandStr - Generates a string made up of randomized
* letters (lower and upper case) and digits, the length
* is a specified parameter.
*/
function generateRandStr($length){
$randstr = "";
for($i=0; $i<$length; $i++){
$randnum = mt_rand(0,61);
if($randnum < 10){
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
}
}
/**
* Initialize session object - This must be initialized before
* the form object because the form uses session variables,
* which cannot be accessed unless the session has started.
*/
$session = new Session($database);
/* Initialize form object */
$form = new Form();
?>
My other problem, and below you'll see the database class, but I have session_start(); at the top of all my pages and for some reason the mix between database and session refuse to actually register or login anyone. Maybe someone could identify a reason why?
<?php
require_once("http://www.walkingspheres.com/definitions.php");
class MySQLDB
{
var $connection; //The MySQL database connection
var $num_active_users; //Number of active users viewing site
var $num_active_guests; //Number of active guests viewing site
var $num_members; //Number of signed-up users
/* Note: call getNumMembers() to access $num_members! */
/* Class constructor */
function MySQLDB(){
/* Make connection to database */
$this->connection = mysql_connect("localhost","name","pass") or die(mysql_error());
mysql_select_db("pen15_users", $this->connection) or die(mysql_error());
/**
* Only query database to find out number of members
* when getNumMembers() is called for the first time,
* until then, default value set.
*/
$this->num_members = -1;
if(TRACK_VISITORS){
/* Calculate number of users at site */
$this->calcNumActiveUsers();
/* Calculate number of guests at site */
$this->calcNumActiveGuests();
}
}
/**
* confirmUserPass - Checks whether or not the given
* username is in the database, if so it checks if the
* given password is the same password in the database
* for that user. If the user doesn't exist or if the
* passwords don't match up, it returns an error code
* (1 or 2). On success it returns 0.
*/
function confirmUserPass($username, $password){
/* Verify that user is in database */
$q = "SELECT password FROM members WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}
/* Retrieve password from result, strip slashes */
$dbarray = mysql_fetch_array($result);
$dbarray['password'] = stripslashes($dbarray['password']);
$password = stripslashes($password);
/* Validate that password is correct */
if($password == $dbarray['password']){
return 0; //Success! Username and password confirmed
}
else{
return 2; //Indicates password failure
}
}
/**
* confirmSessionID - Checks whether or not the given
* username is in the database, if so it checks if the
* given userid is the same userid in the database
* for that user. If the user doesn't exist or if the
* userids don't match up, it returns an error code
* (1 or 2). On success it returns 0.
*/
public function confirmSessionId($username, $sessionid){
/* Add slashes if necessary (for query) */
if(!get_magic_quotes_gpc()) {
$username = addslashes($username);
}
/* Verify that user is in database */
$q = "SELECT sessionid FROM members WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}
/* Retrieve id from result, strip slashes */
$dbarray = mysql_fetch_array($result);
/* Validate that sessionid is correct */
if($sessionid == $dbarray['sessionid']){
return 0; //Success! Username and session confirmed
}
else{
return 2; //Indicates userid invalid
}
}
/**
* usernameTaken - Returns true if the username has
* been taken by another user, false otherwise.
*/
function usernameTaken($username){
$q = "SELECT username FROM members WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
return (mysql_numrows($result) > 0);
}
/**
* usernameBanned - Returns true if the username has
* been banned by the administrator.
*/
function usernameBanned($username){
if(!get_magic_quotes_gpc()){
$username = addslashes($username);
}
$q = "SELECT username FROM banned_users WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
return (mysql_numrows($result) > 0);
}
/**
* addNewUser - Inserts the given (username, password, email)
* info into the database. Appropriate user level is set.
* Returns true on success, false otherwise.
*/
function addNewUser($username,$password,$email,$home,$bday){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, 'pen15') == 0 ||
strcasecmp($username, 'Charlie DeHart')==0 ){
$ulevel = 9;
}else{
$ulevel = 1;
}
$home=trim($home);
$bday=trim($day);
if($home='' || $home=NULL)
$home = 'default';
if($bday='' || $bday=NULL)
$bday = 'default';
$sessionid = '1';
$q = "INSERT INTO members(username, password,";
"email, userlevel, timestamp, home, birthday, sessionid) ";
"VALUES ('$username','$password','$email','$ulevel','$time',";
"'$home','$bday','$sessionid')";
return mysql_query($q, $this->connection);
}
/**
* updateUserField - Updates a field, specified by the field
* parameter, in the user's row of the database.
*/
function updateUserField($username, $field, $value){
$q = "UPDATE members SET ".$field." = '$value' WHERE username = '$username'";
return mysql_query($q, $this->connection);
}
/**
* getUserInfo - Returns the result array from a mysql
* query asking for all information stored regarding
* the given username. If query fails, NULL is returned.
*/
function getUserInfo($username){
$q = "SELECT * FROM members WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
/* Error occurred, return given name by default */
if(!$result || (mysql_numrows($result) < 1)){
return NULL;
}
/* Return result array */
$dbarray = mysql_fetch_array($result);
return $dbarray;
}
}
/* Create database connection */
$database = new MySQLDB;
?>
Thank you very much for any comments, help, or an explanation as to if including a file wich creates a new class at the bottom will call the constructor.
$this->databse = $db;
It should be $this->database
Gotta hate typos eh? Since the assigning of the object property is not being done right, $this->database is null and thus the function (more a method in this case) you're trying to call is undefined.
On another note (since the comment above should fix your current problem): You're exposing yourself to death.
function confirmUserPass($username, $password){
/* Verify that user is in database */
$q = "SELECT password FROM members WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
What if I make $username be something that does some SQL that you do not desire? It wouldn't be hard. Please either use mysql_escape_string (eh, I might be wrong about the exact name of the function, I always work with PDO nowadays) or change your code to prepared statements. Else you will be suffering from SQL injection (http://en.wikipedia.org/wiki/SQL_injection)
Do the same for EVERY single data entry to the DB that was originally submitted by the user (and often even if it was indirectly submitted by a user)
include("http://www.walkingspheres.com/include/database.class.php");
include("http://www.walkingspheres.com/include/mailer.php");
include("http://www.walkingspheres.com/include/form.php");
Yikes!
Wow, do you have allow_url_fopen enabled? It looks like it. That or you have your error reporting level turned way, way down. If these lines of code are working, then your code is exploiting an incorrect PHP setting that may be a huge security hole.
include executes code. You're include-ing URLs. This means that PHP is making web requests to download those files. If someone were able to trick your code into performing an arbitrary include, they could execute their code on your server, and you'd never know.
Those are PHP scripts. It's very likely that they're being executed when the request is made instead of returning the source code, and are instead returning nothing. That or PHP is properly configured, but that your error reporting level is hiding the problem.
Please change all of those include, include_once, require and require_once calls to use paths on the filesystem instead of URLs.
Also turn up your error reporting level during development using the following two lines of code:
ini_set('display_errors', true);
error_reporting(-1);
I'm willing to bet that turning up the error reporting is going to make PHP whine incredibly loudly about the problems you're having, from the serialization issues to the database typo.
Also, could you tell us where you picked up that "Session" class? It's really, really old and people constantly have trouble with it. It's poorly designed and probably should not be used in the modern age. I'd really like to know where it comes from so I can have the author -- *ahem* -- re-educated and/or have datacenter hosting it nuked from orbit.
(Your code is quite long, and I've not tried to understand it all -- but I've seen one thing that feels odd)
You MySQLDB class has its $connection property that is a resource -- as its obtained as the return value of the mysql_connect() function.
Resources cannot be serialized -- see the manual page of serialize() for a reference (quoting) :
serialize() handles all types, except
the resource-type.
I'm guessing the $database property of your Session class points to an instance of your MYSQLDB class -- which contains a resource.
That resource cannot be serialized -- so, it cannot be stored in $_SESSION ; or, more specifically, it cannot be restored from session.
To address this specific point, you should re-connect to your database when the session is loaded -- the __sleep() and __wakeup() magic methods might help, here.