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

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.

Related

user profiles and editing them // session data

Mostly a security question
Currently I am using session variables to determine who is viewing the website and then matching the users session name vs the profile name being viewed. If these match then the profile will be editable (since it is their profile).
I am using:
$pid = $_GET['pid']; // Profile being viewed
$edit = $_GET['edit']; // true/false for editing
$username = $_SESSION['username'];
$pclass = new user_profile($db, $pid, $username);
$pclass just takes my database connection, profile that is being viewed and the user viewering.
class user_profile {
private $db;
private $viewer;
public function __construct(\database $db, $pid, $viewer) {
$this->db = $db;
$this->username = $pid;
$this->viewer = $viewer;
}
}
for displaying the edit button and then allowing the user to view the edit page I use a method myProfile() which is simply:
public function myProfile() {
if($this->username === $this->viewer) {
return true;
}
else {
return false;
}
}
Is this a secure enough way to stop users editing other peoples profiles or is there another way around it how this should be done?
Given the information that you supplied, this is a secure way of doing this.
$_SESSION is something you control on the server, and can't be modified by the user.

Modx Pagelocker logout

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();

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

how to logout facebook in codeigniter framework

How to Logout action performed in my website who are login via facebook
my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
public function Main(){
parent::__construct();
parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
$this->load->library('Facebook', $config);
}
function index(){
// Try to get the user's id on Facebook
$userId = $this->facebook->getUser();
// If user is not yet authenticated, the id will be zero
if($userId == 0){
// Generate a login url
$data['url'] = $this->facebook->getLoginUrl(array('scope'=>'email'));
$this->load->view('main_index', $data);
} else {
// Get user's data and print it
$user = $this->facebook->api('/me');
print_r($user);
}
}
}
?>
my view
Click here to login
config/facebook.php
<?php
$config['appId'] = 'xxxxxxxxxxxxxx';//i have my id like 1411574xxxxxxxxxxxxxx
$config['secret'] = 'xxxxxxxxxx';// i have my id like 2f3917995d2024xxxxxxxxxxxxxx
my library :Facebook.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
require_once "base_facebook.php";
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
const FBSS_COOKIE_NAME = 'fbss';
// We can set this to a high number because the main session
// expiration will trump this.
const FBSS_COOKIE_EXPIRE = 31556926; // 1 year
// Stores the shared session ID if one is set.
protected $sharedSessionID;
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* #param Array $config the application configuration. Additionally
* accepts "sharedSession" as a boolean to turn on a secondary
* cookie for environments with a shared session (that is, your app
* shares the domain with other apps).
* #see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
if (!empty($config['sharedSession'])) {
$this->initSharedSession();
}
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
protected function initSharedSession() {
$cookie_name = $this->getSharedSessionCookieName();
if (isset($_COOKIE[$cookie_name])) {
$data = $this->parseSignedRequest($_COOKIE[$cookie_name]);
if ($data && !empty($data['domain']) &&
self::isAllowedDomain($this->getHttpHost(), $data['domain'])) {
// good case
$this->sharedSessionID = $data['id'];
return;
}
// ignoring potentially unreachable data
}
// evil/corrupt/missing case
$base_domain = $this->getBaseDomain();
$this->sharedSessionID = md5(uniqid(mt_rand(), true));
$cookie_value = $this->makeSignedRequest(
array(
'domain' => $base_domain,
'id' => $this->sharedSessionID,
)
);
$_COOKIE[$cookie_name] = $cookie_value;
if (!headers_sent()) {
$expire = time() + self::FBSS_COOKIE_EXPIRE;
setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain);
} else {
// #codeCoverageIgnoreStart
self::errorLog(
'Shared session ID cookie could not be set! You must ensure you '.
'create the Facebook instance before headers have been sent. This '.
'will cause authentication issues after the first request.'
);
// #codeCoverageIgnoreEnd
}
}
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
if ($this->sharedSessionID) {
$this->deleteSharedSessionCookie();
}
}
protected function deleteSharedSessionCookie() {
$cookie_name = $this->getSharedSessionCookieName();
unset($_COOKIE[$cookie_name]);
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
}
protected function getSharedSessionCookieName() {
return self::FBSS_COOKIE_NAME . '_' . $this->getAppId();
}
protected function constructSessionVariableName($key) {
$parts = array('fb', $this->getAppId(), $key);
if ($this->sharedSessionID) {
array_unshift($parts, $this->sharedSessionID);
}
return implode('_', $parts);
}
}
my library base_facebook.php
my library fb_ca_chain_bundle.crt
now i am log in successfully but unable to logout how to log out implement in this please
Try this link
$params = array( 'next' => 'https://www.myapp.com/after_logout' );
$facebook->getLogoutUrl($params); // $params is optional.
use this in view and access the facebook

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