Confirm Password not working? - php

I have a basic login system and would like to add password and email confirmation to the register form. I made a separate identical box for the confermation password titled "pass_conf" I tried to add code to verify that they matched and it will give an the "Password do not match" error even if they really do match... I am lost. Am I missing something?
everything in code works fine except the password verification
Here is the password verification code:
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}
else{
/* Spruce up password and check length*/
$subpass = stripslashes($subpass);
if(strlen($subpass) < 4){
$form->setError($field, "* Password too short");
}
/* Check if password is not alphanumeric */
else if(!preg_match("/^([0-9a-z])+$/i", ($subpass = trim($subpass)))){
$form->setError($field, "* Password not alphanumeric");
}
else if ($subpass_conf != $subpass) {
$form->setError($field, "* Passwords do not match");
}
}
Here is the entire code from session.php:
<?php
/**
* Session.php
*
* The Session class is meant to simplify the task of keeping
* track of logged in users and also guests.
*
* Please subscribe to our feeds at http://blog.geotitles.com for more such tutorials
*/
include("database.php");
include("mailer.php");
include("form.php");
class Session
{
var $username; //Username given on sign-up
var $userid; //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
/**
* Note: referrer should really only be considered the actual
* page referrer in process.php, any other time it may be
* inaccurate.
*/
/* Class constructor */
function Session(){
$this->time = time();
$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(){
global $database; //The database connection
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;
$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestamp */
else{
$database->addActiveUser($this->username, $this->time);
}
/* Remove inactive visitors from database */
$database->removeInactiveUsers();
$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(){
global $database; //The database connection
/* Check if user has been remembered */
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
$this->username = $_SESSION['username'] = $_COOKIE['cookname'];
$this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
}
/* Username and userid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
$_SESSION['username'] != GUEST_NAME){
/* Confirm that username and userid are valid */
if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['userid']);
return false;
}
/* User is logged in, set class variables */
$this->userinfo = $database->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->userid = $this->userinfo['userid'];
$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){
global $database, $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])*$/i", $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 = $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 = $database->getUserInfo($subuser);
$this->username = $_SESSION['username'] = $this->userinfo['username'];
$this->userid = $_SESSION['userid'] = $this->generateRandID();
$this->userlevel = $this->userinfo['userlevel'];
/* Insert userid into database and update active users table */
$database->updateUserField($this->username, "userid", $this->userid);
$database->addActiveUser($this->username, $this->time);
$database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
/**
* This is the cool part: the user has requested that we remember that
* he's logged in, so we set two cookies. One to hold his username,
* and one to hold his random value userid. It expires by the time
* specified in constants.php. Now, next time he comes to our site, we will
* log him in automatically, but only if he didn't log out before he left.
*/
if($subremember){
setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", $this->userid, 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(){
global $database; //The database connection
/**
* 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['userid']);
/* Reflect fact that user has logged out */
$this->logged_in = false;
/**
* Remove from active users table and add to
* active guests tables.
*/
$database->removeActiveUser($this->username);
$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){
global $database, $form, $mailer; //The database, form and mailer 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{
/* 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])+$/i", $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($database->usernameTaken($subuser)){
$form->setError($field, "* Username already in use");
}
/* Check if username is banned */
else if($database->usernameBanned($subuser)){
$form->setError($field, "* Username banned");
}
}
/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}
else{
/* Spruce up password and check length*/
$subpass = stripslashes($subpass);
if(strlen($subpass) < 4){
$form->setError($field, "* Password too short");
}
/* Check if password is not alphanumeric */
else if(!preg_match("/^([0-9a-z])+$/i", ($subpass = trim($subpass)))){
$form->setError($field, "* Password not alphanumeric");
}
else if ($subpass_conf != $subpass) {
$form->setError($field, "* Passwords do not match");
}
}
/**
* Note: I trimmed the password only after I checked the length
* because if you fill the password field up with spaces
* it looks like a lot more characters than 4, so it looks
* kind of stupid to report "password too short".
*/
/* Email error checking */
$field = "email"; //Use field name for email
if(!$subemail || strlen($subemail = trim($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}$/i";
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 1; //Errors with form
}
/* No errors, add the new account to the */
else{
if($database->addNewUser($subuser, md5($subpass), $subemail)){
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 $database, $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])+$/i", ($subcurpass = trim($subcurpass)))){
$form->setError($field, "* Current Password incorrect");
}
/* Password entered is incorrect */
if($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])+$/i", ($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}$/i";
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){
$database->updateUserField($this->username,"password",md5($subnewpass));
}
/* Change Email */
if($subemail){
$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);
}
/**
* 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 userid.
*/
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;
/* Initialize form object */
$form = new Form;
?>

I honestly think it's the following block that's giving you complications, I've looked over the script a few times now, and am still not seeing where $subpass_conf is being declared, therefore the if statement is returning false giving you an error stating "Passwords do not match" (assuming that IS the error it's showing for you).
else if ($subpass_conf != $subpass) {
$form->setError($field, "* Passwords do not match");
}
You need to figure out why that's not being declared, or try removing that block and seeing if it works first, then adding it back and fixing it.

Ok, Now that my head is a bit clearer, I did some more searching and found the code:
$form->setError($field, "* Passwords do not match");
Threw that in and changed some things to this:
if ($_POST['pass']!= $_POST['pass_conf']) {
$form->setError($field, "* Passwords do not match");
}
and that works perfectly. Thanks again for your help!

$subpass = stripslashes($subpass);
You do not seem to do that for the subpass_conf var.... so you are potentially changing the password field but not changing the password confirmation and so comparison can fail all the time. Depends what stiprslashes does.

Related

No Database Login Form PHP

Can you help me make a code for PHP login no db.
Thanks in advance
Link to Login Form
[Sorry for pastebin link because i'm new to stackover flow]
Here you gone...done!
github.com/panique/php-login-one-file
<?php
/**
* Class OneFileLoginApplication
*
* An entire php application with user registration, login and logout in one file.
* Uses very modern password hashing via the PHP 5.5 password hashing functions.
* This project includes a compatibility file to make these functions available in PHP 5.3.7+ and PHP 5.4+.
*
* #author Panique
* #link https://github.com/panique/php-login-one-file/
* #license http://opensource.org/licenses/MIT MIT License
*/
class OneFileLoginApplication
{
/**
* #var string Type of used database (currently only SQLite, but feel free to expand this with mysql etc)
*/
private $db_type = "sqlite"; //
/**
* #var string Path of the database file (create this with _install.php)
*/
private $db_sqlite_path = "./users.db";
/**
* #var object Database connection
*/
private $db_connection = null;
/**
* #var bool Login status of user
*/
private $user_is_logged_in = false;
/**
* #var string System messages, likes errors, notices, etc.
*/
public $feedback = "";
/**
* Does necessary checks for PHP version and PHP password compatibility library and runs the application
*/
public function __construct()
{
if ($this->performMinimumRequirementsCheck()) {
$this->runApplication();
}
}
/**
* Performs a check for minimum requirements to run this application.
* Does not run the further application when PHP version is lower than 5.3.7
* Does include the PHP password compatibility library when PHP version lower than 5.5.0
* (this library adds the PHP 5.5 password hashing functions to older versions of PHP)
* #return bool Success status of minimum requirements check, default is false
*/
private function performMinimumRequirementsCheck()
{
if (version_compare(PHP_VERSION, '5.3.7', '<')) {
echo "Sorry, Simple PHP Login does not run on a PHP version older than 5.3.7 !";
} elseif (version_compare(PHP_VERSION, '5.5.0', '<')) {
require_once("libraries/password_compatibility_library.php");
return true;
} elseif (version_compare(PHP_VERSION, '5.5.0', '>=')) {
return true;
}
// default return
return false;
}
/**
* This is basically the controller that handles the entire flow of the application.
*/
public function runApplication()
{
// check is user wants to see register page (etc.)
if (isset($_GET["action"]) && $_GET["action"] == "register") {
$this->doRegistration();
$this->showPageRegistration();
} else {
// start the session, always needed!
$this->doStartSession();
// check for possible user interactions (login with session/post data or logout)
$this->performUserLoginAction();
// show "page", according to user's login status
if ($this->getUserLoginStatus()) {
$this->showPageLoggedIn();
} else {
$this->showPageLoginForm();
}
}
}
/**
* Creates a PDO database connection (in this case to a SQLite flat-file database)
* #return bool Database creation success status, false by default
*/
private function createDatabaseConnection()
{
try {
$this->db_connection = new PDO($this->db_type . ':' . $this->db_sqlite_path);
return true;
} catch (PDOException $e) {
$this->feedback = "PDO database connection problem: " . $e->getMessage();
} catch (Exception $e) {
$this->feedback = "General problem: " . $e->getMessage();
}
return false;
}
/**
* Handles the flow of the login/logout process. According to the circumstances, a logout, a login with session
* data or a login with post data will be performed
*/
private function performUserLoginAction()
{
if (isset($_GET["action"]) && $_GET["action"] == "logout") {
$this->doLogout();
} elseif (!empty($_SESSION['user_name']) && ($_SESSION['user_is_logged_in'])) {
$this->doLoginWithSessionData();
} elseif (isset($_POST["login"])) {
$this->doLoginWithPostData();
}
}
/**
* Simply starts the session.
* It's cleaner to put this into a method than writing it directly into runApplication()
*/
private function doStartSession()
{
if(session_status() == PHP_SESSION_NONE) session_start();
}
/**
* Set a marker (NOTE: is this method necessary ?)
*/
private function doLoginWithSessionData()
{
$this->user_is_logged_in = true; // ?
}
/**
* Process flow of login with POST data
*/
private function doLoginWithPostData()
{
if ($this->checkLoginFormDataNotEmpty()) {
if ($this->createDatabaseConnection()) {
$this->checkPasswordCorrectnessAndLogin();
}
}
}
/**
* Logs the user out
*/
private function doLogout()
{
$_SESSION = array();
session_destroy();
$this->user_is_logged_in = false;
$this->feedback = "You were just logged out.";
}
/**
* The registration flow
* #return bool
*/
private function doRegistration()
{
if ($this->checkRegistrationData()) {
if ($this->createDatabaseConnection()) {
$this->createNewUser();
}
}
// default return
return false;
}
/**
* Validates the login form data, checks if username and password are provided
* #return bool Login form data check success state
*/
private function checkLoginFormDataNotEmpty()
{
if (!empty($_POST['user_name']) && !empty($_POST['user_password'])) {
return true;
} elseif (empty($_POST['user_name'])) {
$this->feedback = "Username field was empty.";
} elseif (empty($_POST['user_password'])) {
$this->feedback = "Password field was empty.";
}
// default return
return false;
}
/**
* Checks if user exits, if so: check if provided password matches the one in the database
* #return bool User login success status
*/
private function checkPasswordCorrectnessAndLogin()
{
// remember: the user can log in with username or email address
$sql = 'SELECT user_name, user_email, user_password_hash
FROM users
WHERE user_name = :user_name OR user_email = :user_name
LIMIT 1';
$query = $this->db_connection->prepare($sql);
$query->bindValue(':user_name', $_POST['user_name']);
$query->execute();
// Btw that's the weird way to get num_rows in PDO with SQLite:
// if (count($query->fetchAll(PDO::FETCH_NUM)) == 1) {
// Holy! But that's how it is. $result->numRows() works with SQLite pure, but not with SQLite PDO.
// This is so crappy, but that's how PDO works.
// As there is no numRows() in SQLite/PDO (!!) we have to do it this way:
// If you meet the inventor of PDO, punch him. Seriously.
$result_row = $query->fetchObject();
if ($result_row) {
// using PHP 5.5's password_verify() function to check password
if (password_verify($_POST['user_password'], $result_row->user_password_hash)) {
// write user data into PHP SESSION [a file on your server]
$_SESSION['user_name'] = $result_row->user_name;
$_SESSION['user_email'] = $result_row->user_email;
$_SESSION['user_is_logged_in'] = true;
$this->user_is_logged_in = true;
return true;
} else {
$this->feedback = "Wrong password.";
}
} else {
$this->feedback = "This user does not exist.";
}
// default return
return false;
}
/**
* Validates the user's registration input
* #return bool Success status of user's registration data validation
*/
private function checkRegistrationData()
{
// if no registration form submitted: exit the method
if (!isset($_POST["register"])) {
return false;
}
// validating the input
if (!empty($_POST['user_name'])
&& strlen($_POST['user_name']) <= 64
&& strlen($_POST['user_name']) >= 2
&& preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name'])
&& !empty($_POST['user_email'])
&& strlen($_POST['user_email']) <= 64
&& filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)
&& !empty($_POST['user_password_new'])
&& strlen($_POST['user_password_new']) >= 6
&& !empty($_POST['user_password_repeat'])
&& ($_POST['user_password_new'] === $_POST['user_password_repeat'])
) {
// only this case return true, only this case is valid
return true;
} elseif (empty($_POST['user_name'])) {
$this->feedback = "Empty Username";
} elseif (empty($_POST['user_password_new']) || empty($_POST['user_password_repeat'])) {
$this->feedback = "Empty Password";
} elseif ($_POST['user_password_new'] !== $_POST['user_password_repeat']) {
$this->feedback = "Password and password repeat are not the same";
} elseif (strlen($_POST['user_password_new']) < 6) {
$this->feedback = "Password has a minimum length of 6 characters";
} elseif (strlen($_POST['user_name']) > 64 || strlen($_POST['user_name']) < 2) {
$this->feedback = "Username cannot be shorter than 2 or longer than 64 characters";
} elseif (!preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name'])) {
$this->feedback = "Username does not fit the name scheme: only a-Z and numbers are allowed, 2 to 64 characters";
} elseif (empty($_POST['user_email'])) {
$this->feedback = "Email cannot be empty";
} elseif (strlen($_POST['user_email']) > 64) {
$this->feedback = "Email cannot be longer than 64 characters";
} elseif (!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
$this->feedback = "Your email address is not in a valid email format";
} else {
$this->feedback = "An unknown error occurred.";
}
// default return
return false;
}
/**
* Creates a new user.
* #return bool Success status of user registration
*/
private function createNewUser()
{
// remove html code etc. from username and email
$user_name = htmlentities($_POST['user_name'], ENT_QUOTES);
$user_email = htmlentities($_POST['user_email'], ENT_QUOTES);
$user_password = $_POST['user_password_new'];
// crypt the user's password with the PHP 5.5's password_hash() function, results in a 60 char hash string.
// the constant PASSWORD_DEFAULT comes from PHP 5.5 or the password_compatibility_library
$user_password_hash = password_hash($user_password, PASSWORD_DEFAULT);
$sql = 'SELECT * FROM users WHERE user_name = :user_name OR user_email = :user_email';
$query = $this->db_connection->prepare($sql);
$query->bindValue(':user_name', $user_name);
$query->bindValue(':user_email', $user_email);
$query->execute();
// As there is no numRows() in SQLite/PDO (!!) we have to do it this way:
// If you meet the inventor of PDO, punch him. Seriously.
$result_row = $query->fetchObject();
if ($result_row) {
$this->feedback = "Sorry, that username / email is already taken. Please choose another one.";
} else {
$sql = 'INSERT INTO users (user_name, user_password_hash, user_email)
VALUES(:user_name, :user_password_hash, :user_email)';
$query = $this->db_connection->prepare($sql);
$query->bindValue(':user_name', $user_name);
$query->bindValue(':user_password_hash', $user_password_hash);
$query->bindValue(':user_email', $user_email);
// PDO's execute() gives back TRUE when successful, FALSE when not
// #link http://stackoverflow.com/q/1661863/1114320
$registration_success_state = $query->execute();
if ($registration_success_state) {
$this->feedback = "Your account has been created successfully. You can now log in.";
return true;
} else {
$this->feedback = "Sorry, your registration failed. Please go back and try again.";
}
}
// default return
return false;
}
/**
* Simply returns the current status of the user's login
* #return bool User's login status
*/
public function getUserLoginStatus()
{
return $this->user_is_logged_in;
}
/**
* Simple demo-"page" that will be shown when the user is logged in.
* In a real application you would probably include an html-template here, but for this extremely simple
* demo the "echo" statements are totally okay.
*/
private function showPageLoggedIn()
{
if ($this->feedback) {
echo $this->feedback . "<br/><br/>";
}
echo 'Hello ' . $_SESSION['user_name'] . ', you are logged in.<br/><br/>';
echo 'Log out';
}
/**
* Simple demo-"page" with the login form.
* In a real application you would probably include an html-template here, but for this extremely simple
* demo the "echo" statements are totally okay.
*/
private function showPageLoginForm()
{
if ($this->feedback) {
echo $this->feedback . "<br/><br/>";
}
echo '<h2>Login</h2>';
echo '<form method="post" action="' . $_SERVER['SCRIPT_NAME'] . '" name="loginform">';
echo '<label for="login_input_username">Username (or email)</label> ';
echo '<input id="login_input_username" type="text" name="user_name" required /> ';
echo '<label for="login_input_password">Password</label> ';
echo '<input id="login_input_password" type="password" name="user_password" required /> ';
echo '<input type="submit" name="login" value="Log in" />';
echo '</form>';
echo 'Register new account';
}
/**
* Simple demo-"page" with the registration form.
* In a real application you would probably include an html-template here, but for this extremely simple
* demo the "echo" statements are totally okay.
*/
private function showPageRegistration()
{
if ($this->feedback) {
echo $this->feedback . "<br/><br/>";
}
echo '<h2>Registration</h2>';
echo '<form method="post" action="' . $_SERVER['SCRIPT_NAME'] . '?action=register" name="registerform">';
echo '<label for="login_input_username">Username (only letters and numbers, 2 to 64 characters)</label>';
echo '<input id="login_input_username" type="text" pattern="[a-zA-Z0-9]{2,64}" name="user_name" required />';
echo '<label for="login_input_email">User\'s email</label>';
echo '<input id="login_input_email" type="email" name="user_email" required />';
echo '<label for="login_input_password_new">Password (min. 6 characters)</label>';
echo '<input id="login_input_password_new" class="login_input" type="password" name="user_password_new" pattern=".{6,}" required autocomplete="off" />';
echo '<label for="login_input_password_repeat">Repeat password</label>';
echo '<input id="login_input_password_repeat" class="login_input" type="password" name="user_password_repeat" pattern=".{6,}" required autocomplete="off" />';
echo '<input type="submit" name="register" value="Register" />';
echo '</form>';
echo 'Homepage';
}
}
// run the application
$application = new OneFileLoginApplication();

converting php4 class to php5: help replacing "var $thisvar;" to php5 equivilant

i found a user login script online which i later foundd out had been written in PHP4, and i am in the process of updating it to PHP5 and learning OOP at the same time :)
a snippet of my user class is
<?php
session_start(); //Tell PHP to start the session
include("include/database.php");
include("include/mailer.php");
include("include/form.php");
include("constants.php");
class user
{
var $username; //Username given on sign-up
var $firstname;
var $lastname;
var $userid; //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 $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: referrer should really only be considered the actual
* page referrer in process.php, any other time it may be
* inaccurate.
*/
public function __construct(db $db, Form $form)
{
$this->database = $db;
$this->form = $form;
$this->time = time();
$this->startSession();
$this->num_members = -1;
if(TRACK_VISITORS)
{
/* Calculate number of users at site */
$this->calcNumActiveUsers();
/* Calculate number of guests at site */
$this->calcNumActiveGuests();
}
}
/**
* 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()
{
/* 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->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestamp */
else
{
$this->addActiveUser($this->username, $this->time);
}
/* Remove inactive visitors from database */
$this->removeInactiveUsers();
$this->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->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
}
/* Username and userid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['userid']) && $_SESSION['username'] != GUEST_NAME)
{
/* Confirm that username and userid are valid */
if($this->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0)
{
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['userid']);
return false;
}
/* User is logged in, set class variables */
$this->userinfo = $this->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->userid = $this->userinfo['userid'];
$this->userlevel = $this->userinfo['userlevel'];
$this->lastlogin = $this->userinfo['lastlogin'];
$this->townid = $this->userinfo['placeID'];
return true;
}
/* User not logged in */
else
{
return false;
}
}
}
$db = new db($config);
$form = new Form;
$user = new User($db, $form);
but i've been told the var $username; etc are not very secure and should not be used, so im here to ask what should i use instead?
do i do something like this for each var?
private $username;
/**
* #return the $username
*/
public function getUsername() {
return $this->username;
}
/**
* #param $newUsername
* the username to set
*/
public function setUsername($newUsername) {
$this->username = $newUsername;
}
thanks
var is equivalent to public. By making all the member variables private and adding getters (but not setters) to each of them, you're effectively making it so that other developers who use your API cannot [accidentally] update the values. That's what's meant by "secure" -- it's not as though someone will be able to hack into your server or access data if you don't declare them with the right privacy level*.
If you're going to add a setter as well, I'd say you're wasting your time (although others will disagree with me). You've giving them full reign over the variable anyway. The only advantage is that you can squeeze some other computations in your getter/setter down the road if you decide you want to store the value differently.
* Although another developer might accidentally expose information he shouldn't, such as a password.

my signin form signs people in but doesnt show errors if invalid login attempt

I have a pretty complex login script which contains 4 classes.
The login in form signs people in correctly if the user enters their details correctly but for some reason if they enter incorrect data the error messages fail to show up.
i'll post all my code and try and explain each bit as best i can. :)
ok so my login form
<?php
include("include/user.php");
?>
<h2>Sign In</h2>
<?php
echo $user->form->num_errors; //nothing prints from this so its not getting the value or its not being set correctly?
print_r($_SESSION['error_array']);// this prints out the errors stored in the session correctly
if($form->num_errors > 0)
{
echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";
}?>
<form action="process.php" method="POST">
<table align="left" border="0">
<tr>
<td><span>Email: <?php echo $user->form->error("user"); ?></span></td>
</tr>
<tr>
<td><input type="text" name="user" maxlength="30" value="<?php echo $user->form->value("user"); ?>"></td>
</tr>
<tr>
<td><span>Password: <?php echo $user->form->error("pass"); ?></span></td>
</tr>
<tr>
<td><input type="password" name="pass" maxlength="30" value="<?php echo $user->form->value("pass"); ?>"></td>
</tr>
<tr>
<td colspan="2" align="left"><div class="forgotpass">Forgot Your Password?</div></td>
<td align="right"></td>
</tr>
<tr>
<td colspan="2" align="left"><div class="remember"><label><input type="checkbox" name="remember" <?php if($user->form->value("remember") != ""){ echo "checked"; } ?>>
Remember me </label><br />(Untick this if on a public computer) </div>
<input type="hidden" name="sublogin" value="1"></td>
</tr>
<tr>
<td><input class="button orange" type="submit" value="Login"></td>
</tr>
</table>
</form>
the form action is set to process.php and its sublogin that has been submitted
process.php is
include("include/user.php");
class Process
{
public function __construct()
{
global $user;
/* User submitted login form */
if(isset($_POST['sublogin']))
{
$this->procLogin();
}
/* User submitted registration form */
else if(isset($_POST['subjoin']))
{
$this->procRegister();
}
/* User submitted forgot password form */
else if(isset($_POST['subforgot']))
{
$this->procForgotPass();
}
/* User submitted edit account form */
else if(isset($_POST['subedit']))
{
$this->procEditAccount();
}
/**
* The only other reason user should be directed here
* is if he wants to logout, which means user is
* logged in currently.
*/
else if($user->logged_in)
{
$this->procLogout();
}
/**
* Should not get here, which means user is viewing this page
* by mistake and therefore is redirected.
*/
else
{
header("Location: index.php");
}
}
/**
* procLogin - Processes the user submitted login form, if errors
* are found, the user is redirected to correct the information,
* if not, the user is effectively logged in to the system.
*/
function procLogin()
{
global $user;
/* Login attempt */
$retval = $user->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));
/* Login successful */
if($retval)
{
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'index.php';
header("Location: http://$host$uri/$extra");
}
/* Login failed */
else
{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $user->form->getErrorArray();
header("Location: ".$user->referrer);
}
}
/**
* procLogout - Simply attempts to log the user out of the system
* given that there is no logout form to process.
*/
function procLogout()
{
global $user;
$retval = $user->logout();
header("Location: ".$user->referrer);
#header("Location: main.php");
}
/**
* procRegister - Processes the user submitted registration form,
* if errors are found, the user is redirected to correct the
* information, if not, the user is effectively registered with
* the system and an email is (optionally) sent to the newly
* created user.
*/
function procRegister()
{
global $form, $user;
/* Convert username to all lowercase (by option) */
if(ALL_LOWERCASE)
{
$_POST['email'] = strtolower($_POST['email']);
}
/* Registration attempt */
$retval = $user->register($_POST['email'],$_POST['fname'],$_POST['lname'],$_POST['pass'],$_POST['pass-confirm']);
/* Registration Successful */
if($retval == 0)
{
$_SESSION['reguname'] = $_POST['email'];
$_SESSION['regsuccess'] = true;
header("Location: ".$user->referrer);
}
/* Error found with form */
else if($retval == 1)
{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$user->referrer);
}
/* Registration attempt failed */
else if($retval == 2)
{
$_SESSION['reguname'] = $_POST['email'];
$_SESSION['regsuccess'] = false;
header("Location: ".$user->referrer);
}
}
/**
* procForgotPass - Validates the given username then if
* everything is fine, a new password is generated and
* emailed to the address the user gave on sign up.
*/
function procForgotPass()
{
global $mailer, $form;
/* Username error checking */
$subuser = $_POST['user'];
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0)
{
$form->setError($field, "* Username not entered<br>");
}
else
{
/* Make sure username is in database */
$subuser = stripslashes($subuser);
if(strlen($subuser) < 5 || strlen($subuser) > 30 || !eregi("^([0-9a-z])+$", $subuser) || (!$user->usernameTaken($subuser)))
{
$form->setError($field, "* Username does not exist<br>");
}
}
/* Errors exist, have user correct them */
if($form->num_errors > 0)
{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
}
/* Generate new password and email it to user */
else
{
/* Generate new password */
$newpass = $user->generateRandStr(8);
/* Get email of user */
$usrinf = $user->getUserInfo($subuser);
$email = $usrinf['email'];
/* Attempt to send the email with new password */
if($mailer->sendNewPass($subuser,$email,$newpass))
{
/* Email sent, update database */
$user->updateUserField($subuser, "password", md5($newpass));
$_SESSION['forgotpass'] = true;
}
/* Email failure, do not change password */
else
{
$_SESSION['forgotpass'] = false;
}
}
header("Location: ".$user->referrer);
}
/**
* procEditAccount - Attempts to edit the user's account
* information, including the password, which must be verified
* before a change is made.
*/
function procEditAccount()
{
global $form, $user;
/* Account edit attempt */
$retval = $user->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email']);
/* Account edit successful */
if($retval)
{
$_SESSION['useredit'] = true;
header("Location: ".$user->referrer);
}
/* Error found with form */
else
{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$user->referrer);
}
}
}
/* Initialize process */
$process = new Process($user);
?>
as a result of sublogin submitted the above code calls the $user->login in the user class which is
<?php
include("include/database.php");
include("include/mailer.php");
include("include/form.php");
include("constants.php");
class user
{
var $username; //Username given on sign-up
var $firstname;
var $lastname;
var $userid; //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 $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: referrer should really only be considered the actual
* page referrer in process.php, any other time it may be
* inaccurate.
*/
public function __construct(db $db, Form $form)
{
$this->database = $db;
$this->form = $form;
$this->time = time();
$this->startSession();
$this->num_members = -1;
if(TRACK_VISITORS)
{
/* Calculate number of users at site */
$this->calcNumActiveUsers();
/* Calculate number of guests at site */
$this->calcNumActiveGuests();
}
}
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->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestamp */
else
{
$this->addActiveUser($this->username, $this->time);
}
/* Remove inactive visitors from database */
$this->removeInactiveUsers();
$this->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->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
}
/* Username and userid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['userid']) && $_SESSION['username'] != GUEST_NAME)
{
/* Confirm that username and userid are valid */
if($this->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0)
{
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['userid']);
return false;
}
/* User is logged in, set class variables */
$this->userinfo = $this->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->userid = $this->userinfo['userid'];
$this->userlevel = $this->userinfo['userlevel'];
$this->lastlogin = $this->userinfo['lastlogin'];
$this->townid = $this->userinfo['placeID'];
return true;
}
/* User not logged in */
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 userid.
*/
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;
}
/**
* 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)
{
/* Username error checking */
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0)
{
$this->form->setError($field, "* Username 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}$^";#added ^ at end!!!!!!!!!!!!!!!
if(!preg_match($regex,$subuser))
{
$this->form->setError($field, "* Email invalid");
}
$subuser = stripslashes($subuser);
}
/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass)
{
$this->form->setError($field, "* Password not entered");
}
/* Return if form errors exist */
if($this->form->num_errors > 0)
{
return false;
}
/* Checks that username is in database and password is correct */
$subuser = stripslashes($subuser);
$result = $this->confirmUserPass($subuser, md5($subpass));
/* Check error codes */
if($result == 1)
{
$field = "user";
$this->form->setError($field, "* Username not found");
}
else if($result == 2)
{
$field = "pass";
$this->form->setError($field, "* Invalid password");
}
/* Return if form errors exist */
if($this->form->num_errors > 0)
{
return false;
}
/* Username and password correct, register session variables */
$this->userinfo = $this->getUserInfo($subuser);
$this->username = $_SESSION['username'] = $this->userinfo['username'];
$this->firstname = $_SESSION['firstname'] = $this->userinfo['firstname'];
$this->userid = $_SESSION['userid'] = $this->generateRandID();
$this->userlevel = $this->userinfo['userlevel'];
/* Insert userid into database and update active users table */
$this->updateUserField($this->username, "userid", $this->userid);
$this->addActiveUser($this->username, $this->time);
$this->removeActiveGuest($_SERVER['REMOTE_ADDR']);
/**
* This is the cool part: the user has requested that we remember that
* he's logged in, so we set two cookies. One to hold his username,
* and one to hold his random value userid. It expires by the time
* specified in constants.php. Now, next time he comes to our site, we will
* log him in automatically, but only if he didn't log out before he left.
*/
if($subremember)
{
setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH);
}
/* Login completed successfully */
return true;
}
}
$db = new db($config);
$form = new Form;
$user = new User($db, $form);
?>
and then there is the form class
class Form
{
var $values = array(); //Holds submitted form field values
var $errors = array(); //Holds submitted form error messages
var $num_errors; //The number of errors in submitted form
/* Class constructor */
function __construct()
{
/**
* Get form value and error arrays, used when there
* is an error with a user-submitted form.
*/
if(isset($_SESSION['value_array']) && isset($_SESSION['error_array']))
{
$this->values = $_SESSION['value_array'];
$this->errors = $_SESSION['error_array'];
$this->num_errors = count($this->errors);
unset($_SESSION['value_array']);
unset($_SESSION['error_array']);
}
else
{
$this->num_errors = 0;
}
}
/**
* setValue - Records the value typed into the given
* form field by the user.
*/
function setValue($field, $value)
{
$this->values[$field] = $value;
}
/**
* setError - Records new form error given the form
* field name and the error message attached to it.
*/
function setError($field, $errmsg)
{
$this->errors[$field] = $errmsg;
$this->num_errors = count($this->errors);
}
/**
* value - Returns the value attached to the given
* field, if none exists, the empty string is returned.
*/
function value($field)
{
if(array_key_exists($field,$this->values))
{
return htmlspecialchars(stripslashes($this->values[$field]));
}
else
{
return "";
}
}
/**
* error - Returns the error message attached to the
* given field, if none exists, the empty string is returned.
*/
function error($field)
{
if(array_key_exists($field,$this->errors))
{
return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>";
}
else
{
return "";
}
}
/* getErrorArray - Returns the array of error messages */
function getErrorArray()
{
return $this->errors;
}
}
but for some reason like i say the form errors are not showing up? im new to oop and i realise that my code is not brilliant but im working on it :)
there is also a database class but wont post that unless you need it. have spent ages trying to get this to work but have failed missurably, any help will be greatly appreciated!
edit
i think the problem is to do with the sessions, the reason i think this is because this part of the Form class
if(isset($_SESSION['value_array']) && isset($_SESSION['error_array']))
{
$this->values = $_SESSION['value_array'];
$this->errors = $_SESSION['error_array'];
$this->num_errors = count($this->errors);
unset($_SESSION['value_array']);
unset($_SESSION['error_array']);
}
else
{
$this->num_errors = 0;
}
always sets the num_errors to 0 the if statement always fails, if i change this->num->errors to 3 for example i get a message appear on my form saying 3 errors found. but when i print_r($session) on the signin page it has all the error data stored so there is no reason why the if should fail. any ideas??
thanks
thanks
After several hours of nit picking through the code i wittled the problem dowwn to the $_session varibles. after much trial and error i decided to add $session_start() to my login.php page and everything worked as expected. Not sure why the session_start() in the user class was not sufficient??? but it seems to be sorted.
now on to sorting out those var's :)

Working with PHP Echos and mySQL Count queries amongst others

Just so you have some idea of my system, I have a PASSENGER table that has all the passenger's personal details in (you know surname, first name etc). But it also stores a 'username' and 'groupID' field. The username allows the passenger's details to be linked to the currently logged in user through:-
$loggedinuser = $session->username;
However, all those passengers who belong to one family (or who have booked together) are linked by a GROUP ID. What I would like to do is find out how many people are in a certain group...the group in question being the one linked to the current user!
For example a COUNT mySQL query on the groupID where the groupID = the group ID of the currently logged in user.
This value will then go in a HTML form.
<?php
$loggedinuser = $session->username;
$sql="SELECT count(p.groupID) AS count FROM PASSENGER p WHERE p.username = '$loggedinuser'";
$rows = mysql_num_rows($sql);
{
echo 'Number of Passengers: <input type="text" name="groupno" value = "'.$rows['groupID']. "\" /><br />";
Which is the first part of the code....
I appear to be able to find out the groupID of the currently logged in user through this code:-
$query3 = "SELECT p.groupID FROM PASSENGER p f WHERE p.username = '$loggedinuser'";
$result = mysql_query($query3);
while($row = mysql_fetch_array($result))
{
echo $row['groupID'];
}
}}
echo mysql_error();
But am I able to store the value that is echoed here:-
echo $row['groupID'];
As a variable for example?
AS then, when I want to return all of the similar users in the group (linked by GroupID), I would then have a variable to use, rather than
$sql='SELECT * FROM PASSENGER WHERE groupID="5"';
$query=mysql_query($sql);
$count=mysql_num_rows($query);
while($fetch_arr=mysql_fetch_array($query)){
$familyName=$fetch_arr['surname'];
echo $familyName;
As the first line of the mySQL query would read something along the lines of:-
$sql='SELECT * FROM PASSENGER WHERE groupID='$loggedingroupID'";
I appreciate any help, if you have any questions just comment and I'll be glad to clarify what I mean!
Regards,
Tom
EDIT: Session Class
<?
/**
* Session.php
*
* The Session class is meant to simplify the task of keeping
* track of logged in users and also guests.
*
* Please subscribe to our feeds
*/
include("database.php");
include("mailer.php");
include("form.php");
class Session
{
var $username; //Username given on sign-up
var $userid; //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
/**
* Note: referrer should really only be considered the actual
* page referrer in process.php, any other time it may be
* inaccurate.
*/
/* Class constructor */
function Session() {
$this->time = time();
$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(){
global $database; //The database connection
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;
$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestamp */
else{
$database->addActiveUser($this->username, $this->time);
}
/* Remove inactive visitors from database */
$database->removeInactiveUsers();
$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(){
global $database; //The database connection
/* Check if user has been remembered */
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
$this->username = $_SESSION['username'] = $_COOKIE['cookname'];
$this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
}
/* Username and userid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
$_SESSION['username'] != GUEST_NAME){
/* Confirm that username and userid are valid */
if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['userid']);
return false;
}
/* User is logged in, set class variables */
$this->userinfo = $database->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->userid = $this->userinfo['userid'];
$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){
global $database, $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(!eregi("^([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 = $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 = $database->getUserInfo($subuser);
$this->username = $_SESSION['username'] = $this->userinfo['username'];
$this->userid = $_SESSION['userid'] = $this->generateRandID();
$this->userlevel = $this->userinfo['userlevel'];
/* Insert userid into database and update active users table */
$database->updateUserField($this->username, "userid", $this->userid);
$database->addActiveUser($this->username, $this->time);
$database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
/**
* This is the cool part: the user has requested that we remember that
* he's logged in, so we set two cookies. One to hold his username,
* and one to hold his random value userid. It expires by the time
* specified in constants.php. Now, next time he comes to our site, we will
* log him in automatically, but only if he didn't log out before he left.
*/
if($subremember){
setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", $this->userid, 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(){
global $database; //The database connection
/**
* 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['userid']);
/* Reflect fact that user has logged out */
$this->logged_in = false;
/**
* Remove from active users table and add to
* active guests tables.
*/
$database->removeActiveUser($this->username);
$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){
global $database, $form, $mailer; //The database, form and mailer 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{
/* 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(!eregi("^([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($database->usernameTaken($subuser)){
$form->setError($field, "* Username already in use");
}
/* Check if username is banned */
else if($database->usernameBanned($subuser)){
$form->setError($field, "* Username banned");
}
}
/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}
else{
/* Spruce up password and check length*/
$subpass = stripslashes($subpass);
if(strlen($subpass) < 4){
$form->setError($field, "* Password too short");
}
/* Check if password is not alphanumeric */
else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
$form->setError($field, "* Password not alphanumeric");
}
/**
* Note: I trimmed the password only after I checked the length
* because if you fill the password field up with spaces
* it looks like a lot more characters than 4, so it looks
* kind of stupid to report "password too short".
*/
}
/* Email error checking */
$field = "email"; //Use field name for email
if(!$subemail || strlen($subemail = trim($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(!eregi($regex,$subemail)){
$form->setError($field, "* Email invalid");
}
$subemail = stripslashes($subemail);
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1; //Errors with form
}
/* No errors, add the new account to the */
else{
if($database->addNewUser($subuser, md5($subpass), $subemail)){
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 $database, $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 ||
!eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){
$form->setError($field, "* Current Password incorrect");
}
/* Password entered is incorrect */
if($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(!eregi("^([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(!eregi($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){
$database->updateUserField($this->username,"password",md5($subnewpass));
}
/* Change Email */
if($subemail){
$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);
}
/**
* 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 userid.
*/
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;
/* Initialize form object */
$form = new Form;
?>
anyway. what you could do as well is:
$query3 = "SELECT p.groupID FROM PASSENGER p f WHERE p.username = '$loggedinuser'";
$result = mysql_query($query3);
while($row = mysql_fetch_array($result))
{
$_SESSION['groupID'] = $row['groupID'];
}
echo mysql_error();
then you call it anywhere:
$groupID= $_SESSION['groupID'];
got to run now. if you have problem with above solution, let me know i'll be back in an hour or so, ok?
if i understand rigth you are initially displaying the gruop of the logged user in an html page.
Now when the php script finishes its execution and the html is displayed every variable you set in the script is gone.
When you have another interaction with the same or others php scripts previuos previous script execution variables are not available.
So to reach what you want 2 solutions:
Save the gruop id in session: $_SESSION["gruop"] = $row['groupID'];
Then others php page you call will be able to retreive the gruop and display for example the list of users that share that groupid
Or in the html you display insert an link that point to a page and send it as parameter the group id: href="display_users_by_group.php?gruopid=".$row['groupID']. When you click the link the page display_users_by_group.php can retreive the groupid with $_GET["groupid"]
Do you mean this?
SELECT groupID, COUNT(*) FROM PASSENGER GROUP BY groupID
This will give you groupId and number of people which are in it ...
$sql=mysql_query(SELECT groupID, COUNT(*) as c FROM PASSENGER GROUP BY groupID);
if(mysql_num_rows($sql)>0) while($entry=mysql_fetch_array($sql)) {
$group=$entry['groupId'];
$count=$entry['c'];
$sql2=mysql_query("SELECT user.name FROM PASSENGER WHERE groupID='.$group.'");
if(mysql_num_rows($sql2)>0) while($entry2=mysql_fetch_array($sql2)) {
$user=$entry2['user'];
}
}
Here you have this query and subquery, when you can get list of users in each group.

PHP calling function of a non-object

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.

Categories