Modx Pagelocker logout - php

I made a page that is locked by Pagelocker. This works perfect but now I need a logout link/button. So I made a link which links to a logout.php.
In this logout.php there is following code:
<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header("Location: /login.html");
die;
exit;
?>
It redirects me to login but when I manually go to protected page it is shown without login.
The code which is used to protect the page and start the session is:
<?php
/**
*
* PageLocker
*
* Simple front-end password protection for individual or groups of pages.
*
* # author Aaron Ladage (mods by Bob Ray)
* # version 1.1.0-beta1 - June 21, 2012
*
* PLUGIN PROPERTIES
* &tvPassword - (Required) The TV for the password (default: 'pagePassword')
* &tvPasswordGroup - The TV for the password group (default: 'pagePasswordGroup'). Not required, but a good idea, unless you want all password-protected pages to be accessible with the same password.
* &formResourceID - (Required) The ID of the password form page (no default set, but absolutely necessary -- the plugin will not work without it)
*
**/
/* #var $modx modX */
/* #var $scriptProperties array */
if (!function_exists("toForm")) {
/* Show Login form */
function toForm($resourceId) {
global $modx;
unset($_SESSION['password']); // make sure password is not still set
if ($modx->resource->get('id') != $resourceId) { // prevent infinite loop
$modx->sendForward($resourceId);
}
}
}
// Get the default plugin properties
$tvPassword = $modx->getOption('tvPassword',$scriptProperties,'pagePassword');
$tvPasswordGroup = $modx->getOption('tvPasswordGroup',$scriptProperties,'pagePasswordGroup');
$formResourceID = $modx->getOption('formResourceID', $scriptProperties);
// Get the password and password group values from the page's template variables
$resourcePW = $modx->resource->getTVValue($tvPassword);
$resourceGroup = $modx->resource->getTVValue($tvPasswordGroup);
/* Do nothing if page is not password-protected, or the form page is not set in the properties */
if ((empty($resourcePW)) || (empty($formResourceID))) {
return;
}
// Set additional defaults
$resourceGroup = empty($resourceGroup) ? 0 : $resourceGroup;
$groups = isset($_SESSION['groups'])? $modx->fromJSON($_SESSION['groups']) : array();
/* Get and sanitize the password submitted by the user (if any) */
$userPW = isset($_POST['password'])? filter_var($_POST['password'], FILTER_SANITIZE_STRING) : '';
if (!empty($userPW)) { /* Form was submitted */
if ($userPW == $resourcePW) { /* password matches the page's password */
/* Set the logged in and groups session */
$_SESSION['loggedin'] = 1;
if (! in_array($resourceGroup, $groups)) {
$groups[] = $resourceGroup;
$groupsJSON = $modx->toJSON($groups);
$_SESSION['groups'] = $groupsJSON;
}
return;
} else { // Doesn't match. Back to the form!
toForm($formResourceID);
}
} else { // Form wasn't submitted, so check for logged in and groups sessions
if ( empty($groups) || ! isset($_SESSION['loggedin']) || (! $_SESSION['loggedin'] === 1) || (! in_array($resourceGroup, $groups))) {
toForm($formResourceID);
}
}
I really need help for this.

As explained in the documentation, there is a little more that needs to be done besides making a call to session_destroy to completely obliterate a session.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();

Related

Problem with a specific php session class

I am currently writing a PHP site for myself. Now I am trying to secure my site. Therefor I am using session. I don't want to write one for myself so I searched and found a wonderful example.
<?php
class SessionManager
{
static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
// Set the cookie name
session_name($name . '_Session');
// Set SSL level
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
// Set session cookie options
session_set_cookie_params($limit, $path, $domain, $https, true);
session_start();
// Make sure the session hasn't expired, and destroy it if it has
if(self::validateSession())
{
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking())
{
// Reset session data and regenerate id
$_SESSION = array();
$_SESSION['IPaddress'] = isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session id changing on any request
}elseif(rand(1, 100) <= 5){
self::regenerateSession();
}
}else{
$_SESSION = array();
session_destroy();
session_start();
}
}
/**
* This function regenerates a new ID and invalidates the old session. This should be called whenever permission
* levels for a user change.
*
*/
static function regenerateSession()
{
// If this session is obsolete it means there already is a new id
if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
return;
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
/**
* This function is used to see if a session has expired or not.
*
* #return bool
*/
static protected function validateSession()
{
if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
return false;
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
return false;
return true;
}
/**
* This function checks to make sure a session exists and is coming from the proper host. On new visits and hacking
* attempts this function will return false.
*
* #return bool
*/
static protected function preventHijacking()
{
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
return false;
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']
&& !( strpos($_SESSION['userAgent'], ÔTridentÕ) !== false
&& strpos($_SERVER['HTTP_USER_AGENT'], ÔTridentÕ) !== false))
{
return false;
}
$sessionIpSegment = substr($_SESSION['IPaddress'], 0, 7);
$remoteIpHeader = isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$remoteIpSegment = substr($remoteIpHeader, 0, 7);
if($_SESSION['IPaddress'] != $remoteIpHeader
&& !(in_array($sessionIpSegment, $this->aolProxies) && in_array($remoteIpSegment, $this->aolProxies)))
{
return false;
}
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
return false;
return true;
}
}
?>
I am trying to call the function over:
include 'SessionSafe.php';
SessionManager::sessionStart('InstallationName');
i am testing the session with:
if (!isset($_SESSION['userid'])) {
header('Location: Login.php');
}
Before, I wrote a value in $_SESSION['userid'], but I have the problem that the session variable is empty...
//File1.php
include 'SessionSafe.php';
session_start();
SessionManager::sessionStart('InstallationName');
// file2.php
session_start();
if (!isset($_SESSION['userid'])) {
header('Location: Login.php');
}
You still have to use session start at the top of each php file.

Losing session data in code igniter

I am facing problems with session data. After login to the website, I'm losing session data. I have tired creating sessions in database and also tried native php session class but nothing worked. I have also cleared tmp folder from server.
The website uses code igniter framework and it is hosted on godaddy VPS
Please help me. Thank You...
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class CI_Session {
var $session_id_ttl; // session id time to live (TTL) in seconds
var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)
function CI_Session()
{
$this->object =& get_instance();
log_message('debug', "Native_session Class Initialized");
$this->_sess_run();
}
/**
* Regenerates session id
*/
function regenerate_id()
{
// copy old session data, including its id
$old_session_id = session_id();
$old_session_data = $_SESSION;
// regenerate session id and store it
session_regenerate_id();
$new_session_id = session_id();
// switch to the old session and destroy its storage
session_id($old_session_id);
session_destroy();
// switch back to the new session id and send the cookie
session_id($new_session_id);
session_start();
// restore the old session data into the new session
$_SESSION = $old_session_data;
// update the session creation time
$_SESSION['regenerated'] = time();
// session_write_close() patch based on this thread
// http://www.codeigniter.com/forums/viewthread/1624/
// there is a question mark ?? as to side affects
// end the current session and store session data.
session_write_close();
}
/**
* Destroys the session and erases session storage
*/
function destroy()
{
//unset($_SESSION);
session_unset();
if ( isset( $_COOKIE[session_name()] ) )
{
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}
/**
* Reads given session attribute value
*/
function userdata($item)
{
if($item == 'session_id'){ //added for backward-compatibility
return session_id();
}else{
return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item];
}
}
/**
* Sets session attributes to the given values
*/
function set_userdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$_SESSION[$key] = $val;
}
}
}
/**
* Erases given session attributes
*/
function unset_userdata($newdata = array())
{
if (is_string($newdata))
{
$newdata = array($newdata => '');
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($_SESSION[$key]);
}
}
}
/**
* Starts up the session system for current request
*/
function _sess_run()
{
$session_id_ttl = $this->object->config->item('sess_expiration');
if (is_numeric($session_id_ttl))
{
if ($session_id_ttl > 0)
{
$this->session_id_ttl = $this->object->config->item('sess_expiration');
}
else
{
$this->session_id_ttl = (60*60*24*365*2);
}
}
session_start();
// check if session id needs regeneration
if ( $this->_session_id_expired() )
{
// regenerate session id (session data stays the
// same, but old session storage is destroyed)
$this->regenerate_id();
}
// delete old flashdata (from last request)
//$this->_flashdata_sweep();
// mark all new flashdata as old (data will be deleted before next request)
//$this->_flashdata_mark();
}
/**
* Checks if session has expired
*/
function _session_id_expired()
{
if ( !isset( $_SESSION['regenerated'] ) )
{
$_SESSION['regenerated'] = time();
return false;
}
$expiry_time = time() - $this->session_id_ttl;
if ( $_SESSION['regenerated'] <= $expiry_time )
{
return true;
}
return false;
}
/**
* Sets "flash" data which will be available only in next request (then it will
* be deleted from session). You can use it to implement "Save succeeded" messages
* after redirect.
*/
function set_flashdata($key, $value)
{
$flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($flash_key, $value);
}
/**
* Keeps existing "flash" data available to next request.
*/
function keep_flashdata($key)
{
$old_flash_key = $this->flash_key.':old:'.$key;
$value = $this->userdata($old_flash_key);
$new_flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($new_flash_key, $value);
}
/**
* Returns "flash" data for the given key.
*/
function flashdata($key)
{
$flash_key = $this->flash_key.':old:'.$key;
return $this->userdata($flash_key);
}
/**
* PRIVATE: Internal method - marks "flash" session attributes as 'old'
*/
function _flashdata_mark()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) == 2)
{
$new_name = $this->flash_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}
/**
* PRIVATE: Internal method - removes "flash" session marked as 'old'
*/
function _flashdata_sweep()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':old:', $name);
if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flash_key)
{
$this->unset_userdata($name);
}
}
}
}
Always prefer to create sessions based on the framework's format. Even I too had the same problem. At that time I was using codeigniter version 2.0, so I used the frameworks session definitions. But as far as I know $_SESSION global variable is supported in version 3
Adding Custom Session Data
$this->session->userdata('item');
$this->session->set_userdata($array);
Retrieving Session Data
$this->session->userdata('item');
Retrieving All Session Data
$this->session->all_userdata()
Removing Session Data
$this->session->unset_userdata('some_name');
Check this documentation, you could get a clear view
https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
When there are any page redirections, keep "exit" after redirect code.
That is how I solved my problem (losing session data after page redirection). See the below example.
header("Location: example.php");
exit;

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 :)

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