Adding new PHP session variable is destroying the session - php

I have encountered an odd issue that I was hoping someone could shed some light on.
I have a website that uses a PHP session to store login details. On this site is a game that also uses PHP session variables. Whenever I have not logged in to the site for a while, then try to play the game it logs me out. If I log back in straight away the session variables are remembered, I stay logged in and I can play the game as many times as I like. I can access any other page on the site with no issues.
I have session_start at the top of all pages. Any thoughts? Thank you.
This is my init.php file:
<?php
ob_start();
session_start();
//error_reporting(0); // don't display errors
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
require 'functions/items.php';
require 'functions/creatures.php';
$current_file = explode('/', $_SERVER['SCRIPT_NAME']);
$current_file = end($current_file);
if (logged_in() === true){
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'password_recover', 'type', 'allow_email', 'profile', 'coins');
$creature_data = creature_data($session_user_id, 'base_creature_id', 'level', 'strength', 'speed', 'intelligence', 'happiness', 'status', 'battle_level');
if(user_active($user_data['username']) === false) {
session_destroy();
header('Location: logout.php');
exit();
}
if($current_file !== 'changepassword.php' && $user_data['password_recover'] == 1){
header('Location: changepassword.php?force');
exit();
}
}
$errors = array();
?>
And here is the game file:
<?php
require_once('core.php');
Hangman::StartPage();
?>
<head>
<link rel="stylesheet" type="text/css" href="games/plank/styles.css" />
</head>
<?php Hangman::PrintGameState(); ?>
<div id="content">
<!--<div id="banner"><img src="games/plank/images/interface/banner.png" /></div>-->
<div id="innerContent">
<div id="wordArea">
<span class="alphabet">
<?php Hangman::PrintCurrentWord(); ?>
</span>
</div>
<span id="controls">
<?php if(isset($_GET['finished']) === true && empty($_GET['finished']) === true){ ?>
<img id="result" src="games/plank/images/interface/<?php echo Hangman::GameResult() ? 'win' : 'lose'; ?>.png" />
<a id="replay" href="http://www.mobbipets.com/site/walkthepalm.php?m=r"></a>
<?php }
else if (Hangman::IsGameFinished()) {
header('Location: walkthepalm.php?finished');
if (Hangman::GameResult() == 'win'){
update_coins($session_user_id, 50);
}
}
else { ?>
<span class="alphabet">
<?php Hangman::PrintKeyboard(); ?>
</span>
<?php } ?>
</span>
<span id="hangman"><img src="games/plank/images/hangman/<?php echo $_SESSION['gameState']; ?>.png" /></span>
</div>
</div>
<?php Hangman::EndPage(); ?>
And here is the core.php file the game uses.
<?php
require_once('db.php');
/*=================================================
this class handles game logic and php sessions.
==================================================*/
abstract class Hangman
{
private static $pageUrl = 'http://www.mobbipets.com/site/walkthepalm.php';
private static $gameStates = 8; //includes the game over state
private static $keyboardButtons = "abcdefghijklmnopqrstuvwxyz&'-";
private static $underscores = array(
'us_1',
'us_2',
'us_3',
);
private static $alphabetAliases = array(
'&' => 'amp',
'\'' => 'apos',
'-' => 'hyphen',
',' => 'comma',
'!' => 'exclaim',
'+' => 'plus',
'?' => 'question',
);
//just checks if we have a valid session
public static function IsLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
private static function RegenerateSession()
{
//session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['lastActivity'] = time();
$_SESSION['word'] = Database::GetRandomWord();
$_SESSION['lettersLeft'] = strlen($_SESSION['word']);
$_SESSION['guessedLetters'] = '';
$_SESSION['gameState'] = 1;
// $session_user_id = $_SESSION['user_id'];
}
//session handling
public static function StartPage()
{
//session_start();
//terminate the session if we've been inactive for more than 10 minutes
if (self::IsLoggedIn())
{
if (isset($_SESSION['lastActivity']) && ((time() - $_SESSION['lastActivity']) > 600 ))
self::EndSession();
else
$_SESSION['lastActivity'] = time();
}
//if logged in after timeout check
if (self::IsLoggedIn())
{
$mode = trim(#$_GET['m']);
if ($mode != '')
$mode = strtolower($mode);
if ($mode != '') //we've passed a special input 'mode'
{
switch ($mode)
{
case 'g': //player making a guess
$guess = trim(#$_GET['g']);
if ($guess != '')
{
$guess = self::FromAlias(strtolower($guess));
if (strlen($guess) == 1 && stripos($_SESSION['guessedLetters'],$guess) === false) //valid
{
$_SESSION['guessedLetters'] .= $guess;
if (stripos($_SESSION['word'],$guess) === false) //wrong guess
$_SESSION['gameState']++;
else
$_SESSION['lettersLeft'] -= substr_count($_SESSION['word'] ,$guess);
}
}
break;
case 'r': //forced reset of session
self::EndSession();
break;
}
}
}
//we forced a reset
if (!self::IsLoggedIn())
{
self::RegenerateSession();
header ('Location: '.self::$pageUrl);
}
}
//is the game finished
public static function IsGameFinished()
{
return $_SESSION['gameState'] >= self::$gameStates || (isset($_SESSION['lettersLeft']) && $_SESSION['lettersLeft'] <= 0);
}
//check if we won (true == win)
public static function GameResult()
{
return $_SESSION['gameState'] < self::$gameStates && $_SESSION['lettersLeft'] == 0;
}
//add any page-close stuff here
public static function EndPage()
{
}
//terminates the session
private static function EndSession()
{
//$_SESSION = array(); //destroy all of the session variables
//session_destroy();
//session_unset();
self::RegenerateSession();
return true;
}
//convert a character to it's alias
private static function ToAlias($letter)
{
return array_key_exists($letter, self::$alphabetAliases) ? self::$alphabetAliases[$letter] : $letter;
}
//reduce an alias to it's corresponding character
private static function FromAlias($alias)
{
$key = array_search($alias, self::$alphabetAliases);
return $key === false ? $alias : $key;
}
//spit out the current word images based on game state
public static function PrintCurrentWord()
{
if (!self::IsLoggedIn())
return;
$finished = self::IsGameFinished();
for ($i = 0; $i < strlen($_SESSION['word']); $i++)
{
$letter = substr($_SESSION['word'],$i,1);
echo '<span class="';
if (!$finished && stripos($_SESSION['guessedLetters'], $letter) === false) //haven't guessed this yet
echo self::$underscores[rand(0,count(self::$underscores)-1)];
else //is a valid character that we've guessed already
echo self::ToAlias($letter);
echo '"></span>'."\n";
}
}
public static function PrintGameState() //debugging
{
echo "\n<!--\n";
echo "Word: ".$_SESSION['word']."\n";
echo "Letters guessed: ".$_SESSION['guessedLetters']."\n";
echo "Letters left: ".$_SESSION['lettersLeft']."\n";
echo "Game State: ".$_SESSION['gameState']."\n";
echo "-->\n";
}
//print out the keyboard buttons
public static function PrintKeyboard()
{
if (!self::IsLoggedIn())
return;
for ($i = 0; $i < strlen(self::$keyboardButtons); $i++)
{
$key = substr(self::$keyboardButtons,$i,1);
$keyAlias = self::ToAlias($key);
if (stripos($_SESSION['guessedLetters'], $key) === false) //haven't guessed this yet
echo '<a class="'.$keyAlias.'" href="?m=g&g='.$keyAlias.'"></a>';
else //we've guessed already
echo '<span class="'.$keyAlias.'"><img src="games/plank/images/alphabet/'.(stripos($_SESSION['word'], $key) === false?'wrong':'right').'.png" /></span>';
echo "\n";
}
}
}
?>

A common mistake is an assignment like this:
$_SESSION = $data;
this will overwrite any previously stored information.
Better practice is to make $_SESSION an array with named indexes:
$_SESSION['somedata'] = $data;
Now you will only overwrite data stored in the 'somedata' field.

Related

If else condition, return value

I'm searching in user profile if there's a string inside appetit with the word demi.
$user = JFactory::getUser();
$profile = JUserHelper::getProfile($user->id);
$prixa = $profile->profile['appetit'];
if (strpos($prixa,'demi') !== false) {
$prix=6;
} else {
$prix=7;
}
seems to be working as expected. Below is a test case code I ran.
<?php
$prixa = 'emimore';
if (strpos($prixa,'demi') !== false) {
$prix=6;
} else {
$prix=7;
}
echo $prix;
?>

Concrete5 8.3 implement Ajax other view

I have a problem recovering a variable in a view.
I followed this tutorial:
Once I have the other view, I can not send a variable so that I can get it back in the view.
Controller.php
public function action_like($token = false, $bID = false)
{
if ($this->bID != $bID) {
return false;
}
if (Core::make('token')->validate('like_page', $token)) {
$page = Page::getCurrentPage();
$u = new User();
$this->markLike($page->getCollectionID(), $page->getCollectionTypeID(), $u->getUserID());
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$b = $this->getBlockObject();
//Normaly we set a variable for get in the view
// $this->set('test', 'test');
$bv = new BlockView($b);
$bv->render('view/view');
} else {
Redirect::page($page)->send();
}
}
exit;
}
view/view.php
<?php echo $test; ?>
<p> Title <p/>
thanks for answers
Sessions provide a way to store information across multiple
requests/pages.
You may use :
//...
$_SESSION["test"] = "test";
//...

PHP undefined variable when url identifier is present

I apologize for this being a bit lengthy but I wanted to show the code and not leave anything out.
The Goal: The user submits a registration form that submits the form to a database which adds the info plus a unique string to the database. Once the user submits an email is sent to the user that contains a link to a php page that has that unique string as a URL identifier at the end like so:
xyz.com/activate.php?uid=292ca78b727593baad9a
When the user clicks that link they are taken that page where they will fill out another form and when they click submit it will activate their account.
The Problem: When the user goes to the link provided they receive an error from my validation page like so:
Undefined index: variable in process.php
BUT when the user deletes the URL identifier so the URL shows as:
xyz.com/activate.php
The user does not receive an error and the validation page (process.php) works properly. I have attempted to use the identifier with a $_GET['uid'] and checking if it exists before running the code but the result was the same. I cannot find an answer when attempting to google this issue so I apologize if this has been asked before.
The Question: Why does this work without the URL identifier but not with it? I do realize the URL identifier basically does a $_REQUEST when the page first loads which is what runs the process.php. Is there a way to prevent that?
So that you guys know the code I am working with I have posted it below.
activate.php:
<?php
// validate the form.
require_once('process.php');
$validation_rules = array(
'company_name' => array(
'required' => true,
'min-length' => 2
)
);
$db_error = '';
$validate = new validator();
$validate->validate($validation_rules);
if ($validate->validate_result()) {
// the validation passed!
}
?>
<div class="bg v-100 cm-hero-activate">
<div class="v-100">
<div class="v-set v-mid">
<form class="v-mid v-bg-white <?php if(!$validate->validate_result() && $_POST || !empty($error)) { echo "shake"; } ?>" name="activation" action="" method="post">
<fieldset>
<div class="form-content">
<div id="content">
<div class="form-inner in" data-id="1" data-name="activate">
<h1>ACTIVATE YOUR ACCOUNT</h1>
<div class="form-section">
<h2>Personal Info</h2>
<?php if (!empty($db_error)) {
echo $db_error;
} ?>
<div class="field-group">
<input type="text" id="company_name" class="field required" name="company_name" value="<?php $validate->form_value('company_name'); ?>">
<label for="company_name" class="placeholder">Company Name</label>
<?php $validate->error(array('field' => 'company_name', 'display_error' => 'single')); ?>
</div>
</div>
<div class="field-bottom">
<button name="submit" data-name="activate" class="bttn btn-dark btn-hover-gloss">ACTIVATE MY ACCOUNT</button>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
process.php:
<?php
class validator {
private $validation_rules;
private $errors = array();
private $validate_result = array();
public function validate($rules) {
$this->validation_rules = $rules;
if($this->validation_rules && $_REQUEST) {
foreach($this->validation_rules as $field => $rules) {
$result = $this->process_validation($field, $rules);
if($result == false) {
$this->validate_result[] = 0;
} elseif($result == true) {
$this->validate_result[] = 1;
}
}
}
}
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
public function validate_result() {
if($this->validation_rules) {
if($_REQUEST) {
$final_result = true;
$length = count($this->validate_result);
for($i=0;$i < $length; $i++) {
if($this->validate_result[$i] == 0) {
$final_result = false;
}
}
return $final_result;
}
}
}
private function process_validation($field, $rules) {
$result = true;
$error = array();
foreach($rules as $rule => $value) {
if($rule == 'required' && $value == true) {
if(!$this->required($field, $value)) {
$error[] = "$field - required";
$result = false;
}
} elseif($rule == 'min-length') {
if(!$this->minlength($field, $value)) {
$error[] = "$field - minimun length is $value";
$result = false;
}
}
}
$this->errors[] = array($field => $error);
return $result;
}
public function error($data = '') {
if($this->validation_rules) {
if($_REQUEST) {
foreach($this->errors as $err) {
if(isset($data['field'])) {
foreach($err as $field => $field_error) {
if($data['field'] == $field) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next:
}
}
} else {
foreach($err as $field => $field_error) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next1;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next1:
}
}
}
}
}
}
private function required($field, $value) {
if(empty($_REQUEST[$field])) {
return false;
} else {
return true;
}
}
private function minlength($field, $value) {
if(strlen($_REQUEST[$field]) < $value) {
return false;
} else {
return true;
}
}
?>
EDIT: it seems that the error is happening on the if statement in the min-length function: if(strlen($_REQUEST[$field]) < $value)
EDIT 2: This may also be of some use. The textbox is being filled with this: <br /><font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'><tr><th align='left' bgcolor='#f57900' colspan=
and underneath that I receive this error: Notice: Undefined index: company_name in C:\...\process.php on line 25 Call Stack #TimeMemoryFunctionLocation 10.0005369632{main}( )...\activate.php:0 20.0029403928validator->form_value( )...\activate.php:80 ">
Your $field_name doesn't exist in the $_REQUEST array which is why you are getting your undefined index error.
You are not checking if the value is set - just accessing it via $_REQUEST[$field_name] in your if statement.
Change
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
To
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && isset($_REQUEST[$field_name])) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
Unrelated Tips.
Aim for cleaner - and more concise readable code.
$input = [
'name' => 'Matthew',
];
$rules = [
'name' => 'required|string',
];
$v = (new Validator())->validate($input, $rules);
if ($v->fails()) {
// Do something with $v->errors();
return;
}
// Do something with validated input
Try and avoid using else or elseif wherever possible. This can be achieved by looking for the negative first, and exiting early. Try not to have too many levels of nesting. It makes your code extremely difficult to read and increases cyclomatic complexity.
Also - take a look at an MVC framework which should help you to structure your code. A good start would be something like Laravel https://laravel.com/ there are good tutorials on https://laracasts.com/
You are getting this error because you have logic like
if($this->validation_rules && $_REQUEST) {
In PHP, an empty array is falsy and a non-empty one, truthy.
$_REQUEST is a combination of $_GET, $_POST and $_COOKIE.
When you add the uid query parameter, $_REQUEST will not be empty and therefore not falsy and your validator will attempt to run but without the expected POST data (such as company_name).
If you're only wanting to validate POST data, you should only be inspecting $_POST.
See Gravy's answer for safer ways to check for the existence of array keys.

login session reading flatfile

I found this amazing code for flatfile login session:
<?php class Login {
// ATTRIBUTES
// User-modifiable:
var $userFile = 'users.txt'; // pathname of user login data file
var $homePage = ""; // // redirect to this URI after logout
// Do not modify below this line....
var $formData = array();
var $userData = array();
// Constructor
function Login() {
// init formData values:
$this->formData['loginId'] = "";
$this->formData['loginPassword'] = "";
$this->formData['loginAccess'] = "";
// start session
session_start();
// handle logout request:
if(!empty($_POST['logout']) or !empty($_GET['logout'])) {
$this->logout(); }
// handle login request:
elseif(isset($_POST['log_in']) and $this->validateLogin()) {
return(TRUE); } // successful login
// see if we're already logged in:
elseif(!empty($_SESSION['loginId'])) {
return(TRUE); } // already logged in
// display the login form instead of the requested page:
$this->loginForm();
exit; }
// end constructor
/* Bool validateLogin() returns TRUE if login/password are valid. Returns FALSE and sets $this->errorMessage if invalid or other error. */
function validateLogin() {
$this->errorMessage = '';
$this->processLoginInput();
if($this->parseUserFile()) {
if(isset($this->userData[$_POST['name']]) and md5($_POST['password']) == $this->userData[$_POST['name']]['password']) {
$_SESSION['loginId'] = $_POST['name'];
$_SESSION['admin'] = $this->userData[$_POST['name']]['admin'];
return(TRUE); }
else { $this->errorMessage = "Invalid user name and/or password"; } }
else { $this->errorMessage = "Unable to read user login data file"; }
return(FALSE); }
// end validateLogin()
/* Mixed parseUserFile(). Returns number of users in userFile, else FALSE */
function parseUserFile() {
$this->userData = array();
if(is_readable($this->userFile)) {
$lines = file($this->userFile);
foreach($lines as $line) {
$line = trim($line);
if($line == "") { continue; }
$parts = preg_split('/\s+/', trim($line));
if(count($parts) >= 3) {
list($user, $password, $admin) = $parts;
$this->userData[$user]['password'] = $password;
$this->userData[$user]['admin'] = $admin; } } }
return((count($this->userData)) ? count($this->userData) : FALSE ); }
// end parseUserFile()
/* Bool loginForm(). Outputs login form HTML. Returns TRUE. */
function loginForm() {
echo <<<EOD
<form action="{$_SERVER['PHP_SELF']}" method="post">
EOD;
if(!empty($this->errorMessage)) { echo "<p id='error'>".$this->errorMessage."</p>\n"; }
echo <<<EOD
<input type="text" name="name" id="name" size="16">
<input type="password" name="password" id="password" size="16">
<input type="submit" name="log_in" id="log_in" value="Log In">
</form>
EOD;
return(TRUE); }
// end loginForm()
/* Int processLoginInput(). Cleans up and sanitizes $_POST data. Returns number of elements in $_POST array. */
function processLoginInput() {
foreach($_POST as $key => $value) {
if(isset($this->formData[$key])) {
if(get_magic_quotes_gpc()) {
$value = stripslashes($value); }
$this->formData[$key] = htmlentities(trim($value)); } }
return(count($_POST)); }
// end processLoginInput()
/* Bool logout(). Logs out user. Returns TRUE or redirects and exits. */
function logout() {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/'); }
session_destroy();
if(!empty($this->homePage)) {
header("Location: " . $this->homePage);
exit; }
return(TRUE); }
// end logout()
} // end class Login
// Instantiate it:
$login = new Login(); ?>
This is the users.txt file which contains the user, the password coded in md5 and whether they are admin (1) or not(0). [admin, password] [user1, password1] [user2, password2]
admin 5f4dcc3b5aa765d61d8327deb882cf99 1
user1 7c6a180b36896a0a8c02787eeafb0e4c 0
user2 6cb75f652a9b52798eb6cf2201057c73 0
MY QUESTION: I want to remove the user from the login, I mean, to recquire only the password to login. I tried this:
/* Bool validateLogin() returns TRUE if login/password are valid. Returns FALSE and sets $this->errorMessage if invalid or other error. */
function validateLogin() {
$this->errorMessage = '';
$this->processLoginInput();
if($this->parseUserFile()) {
if(md5($_POST['password']) == $this->userData['password']) { //removed if(isset($this->userData[$_POST['name']]) and [$_POST['name']]
$_SESSION['loginId'] = $_POST['password']; //changed 'name' for 'password'
$_SESSION['admin'] = $this->userData['admin']; //removeded [$_POST['name']]
return(TRUE); }
else { $this->errorMessage = "Invalid user name and/or password"; } }
else { $this->errorMessage = "Unable to read user login data file"; }
return(FALSE); }
// end validateLogin()
/* Mixed parseUserFile(). Returns number of users in userFile, else FALSE */
function parseUserFile() {
$this->userData = array();
if(is_readable($this->userFile)) {
$lines = file($this->userFile);
foreach($lines as $line) {
$line = trim($line);
if($line == "") { continue; }
$parts = preg_split('/\s+/', trim($line));
if(count($parts) >= 3) {
list($user, $password, $admin) = $parts;
$this->userData['password'] = $password; //removed [$user]
$this->userData[$user]['admin'] = $admin; } } }
return((count($this->userData)) ? count($this->userData) : FALSE ); }
// end parseUserFile()
It works BUT only with the last password in the list, the rest of the passwords dont work. ANY HELP? Where am i mistaken? XXX

error returning information using php

I am steps away from finishing this project, I seem to have a problem with my logic in my fetchMessage() function, I am passing in the session_id however I am getting nothing returned here is my function code
function fetchMessages($session)
{
$get = ("SELECT * FROM chatRoom WHERE session_id = '$session'");
$hold = mysql_query($get, $con);
if($hold)
{
return mysql_fetch_array($hold);
}
}
the code calling this function is
<?php
include 'core/conection.php';
include 'function.php';
if(isset($_POST['method']) === true && empty($_POST['method']) === false)
{
$method = trim($_POST['method']);
$session = trim($_POST['session']);
if($method === 'fetch')
{
$messages = fetchMessages($session);
if(empty($messages) === true)
{
echo 'A representative will be with you shortly';
echo '<br />';
echo $session;
}else
{
foreach($messages as $message)
{
$ts = $message['timestamp'];
?>
<div class = "message">
<?php echo date('n-j-Y h:i:s a', $ts); ?>
<?php echo $message['username']; ?>
says:<p><?php echo nl2br($message['message']); ?></p>
</div>
<?php
}
}
}
}
?>
I know it is making it at least this far because at this line
if(empty($messages) === true)
{
echo 'A representative will be with you shortly';
echo '<br />';
echo $session;
}
it displays the correct session_id i have a fealing it is either my fetchMessages function that is wrong or the html code to display the results that is wrong.

Categories