Here's the code:
final public function login($email) {
$this->email = mysql_real_escape_string($email);
$this->q = "SELECT id FROM users WHERE mail = '$this->email'";
$this->r = mysql_query($this->q);
$this->id = mysql_result($this->r, 0);
$_SESSION['id'] = "$this->id";
header('Location: me.php');
exit;
}
I'm not sure when I redirect the session does not stay. I've echoed it on the current page and it showed. Any solutions? I have a global namespace so the session is set in all files.
Whenever you're dealing with Sessions in PHP, you should use session_start() to load session data into memory.
Call session_start() only once per you page.
Related
I am developing system with sessions in which I have put the code to start session after successful login and assigned values to session variables like $_SESSION['email']. Also, I have put a session destroy code, but the session doesn't seem to destroy. I have following files - index.php
This file grants the access to user for correct credentials with following code:
if(password_verify($password,$dbpass)){
$stmt = $conn->prepare("SELECT name, image FROM admins WHERE email=?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($name,$image);
$stmt->fetch();
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['image'] = $image;
header("Location:insert.php");
}
It works fine by setting session variables and redirects to intended file. In the file insert.php, I have imported file session.php which has below code:
session_start();
if(!isset($_SESSION['email'])){
header("Location:index.php");
}
also, I have a logout.php file which has following code:
if(isset($_SESSION['email'])){
session_destroy();
}
header("Location: index.php");
After running logout.php, if i again tries to access file insert.php, it opens, though the session file is imported in it. It should be redirected to index.php file. What is going wrong? Anyone please help.
Your session and your $_SESSION server variables are seperate.
The session will be broken but the variable won't be empty.
Try this:
session_start();
session_destroy();
//Now you can choose whether you want to unset all sessions, or specific one(s):
$unset_sessions = ['email'];
foreach($_SESSION as $session => $session_value) {
if (in_array($session, $unset_sessions))
unset($_SESSION[$session]);
}
//Or all of them:
$_SESSION = [];
Thought it'd be fun to also create a function out of this:
function breakSessions($specifics= []) {
if (!empty($specific)) { //Handle specifics
foreach($_SESSION as $session => $session_value) {
if (in_array($session, $specifics))
unset($_SESSION[$session]);
}
} else {
$_SESSION = [];
}
}
breakSessions(['login', 'remember_me']) //Specifics;
breakSessions(); //All of them```
if(isset($_SESSION['email'])){
session_start();
session_destroy();
}
header("Location: index.php");
You can't destroy a session without having "start" before. It's reccomended to have a session file which contains "session_start();" which you build templates from so that every page always have "session_start();"
I am trying to create a login controller for my website ... in terms of keeping people logged in I've decided to use sessions.
I am currently attempting to create a class that can be referenced when I include the controller file of the sessions. This will allow me to create, authenticate (delete) and update sessions.
<?php
class Session {
static function start($name, $value) {
session_start();
$_SESSION[$name] = $value;
$_SESSION['EXPIRE'] = time() + 10;
}
// checking for expire
static function auth() {
if (isset($_SESSION['EXPIRE']) && $_SESSION['EXPIRE'] < time()) {
$_SESSION = array();
session_destroy();
}
}
static function update($time = 20) {
if (isset($_SESSION['EXPIRE'])) {
$_SESSION['EXPIRE'] = time() + $time;
session_regenerate_id(false);
}
}
}
Currently it does not set sessions properly. When I try to call the sessions on pages once I set them it does not fetch properly.
The session isn't expiring before I call it because I never call the function that expires it inside the class on the document.
You can't call your Session class as you need to include session_start() and you are only having this in the start method.
Option 1: You would have to call session_start() in each page where you want to deal with sessions
Option 2: Add a function to your class and call it after your class is created and add in there session_start() so wherever you include the Session Class session_start would already been initialized
Example:
Sessions.php
class Session {
static function init(){
session_start();
}
//rest of your methods...
}
//initialize it
Session::init();
page-that-uses-session.php
include('Sessions.php');
Session::update();
Better set php session timeout variable in php.ini or from ini_set() function and don't create own $_SESSION['expire'] variable; You can regenerate_session_id() each time when user sent request; Better test user ip address in session. In most projects you have one page on server or only your own pages.
Set user id in session:
$_SESSION['userid'] = $loggoed_id_from_db;
// and test
if((int)$_SESSION['userid'] == 0){
header('Location: logout.php');
exit;
}else{
if(empty($_SESSION['ip'])){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}else{
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']){
header('Location: logout.php');
exit;
}
}
}
And probably you don't start session from class!
I'm developing app for Facebook. Here when user open application should be checked If user already exists in database. I think I will use $_SESSIONto pass user's Id to checkIfExsists.php
So my FacebookGetId.php looks like:
<?php
...
$id = $user_profile['id'];
$_SESSION['id'] = $id;
?>
So $id for now is i.e. '12345' I just don't know how to make automatically redirect to checkIfExsists.php to check If that Id already exsists in database.
It should be something like: When application is launched, It should take User's Id and automatically redirect to checkIfExsists.phpand pass that Id.
If user exists checkIfExsists.php should redirect user to application.php, if not exists - It should redirect to registration.php
Use the header function
<?php
...
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location: checkIfExsists.php?id='.$id);
?>
on the checkIfExsists.php get the variable with
$id = $_GET["id"];
That would solve your problem the way you want it to be solved, but, this isnĀ“t neccesarilly the way it should be solved, maybe inside checkIfExists.php should be a class instead of structured code with a public function to check existance checkExistance, so you will then just need:
include_once(checkIfExists.php);
$check = new checker();
$exists = $check->checkExistance($id) ;
this way you do not have to be jumping between files and you can have a better way to re-use code,
regards.
Use this:
<?php
session_start();
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location: checkIfExsists.php');
?>
And on the checkIfExsists.php page, retrieve the variable so:
<?php
session_start();
$id = $_SESSION['id'];
?>
Use header('Location:url_of_your_page.php?fbid='.$id). php header function
FacebookGetId.php
<?php
...
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location:checkIfExsists.php?fbid='.$id)
?>
you can do it via GET and header for example :)
header('Location: checkIfExists.php?userID=12345');
in checkIfExists.php
echo $_GET["userID"]
or in checkIfExists.php just start sessions a load ID from session :)
I've looked at existing answers for my problem.
I've echo'd the value right through the process and right up until the "header('Location" instruction the values remain intact.
I don't think it's a serialization problem as suggested for similar problems...
Here are the relevant bits of the class:
class clsSetUser {
protected $UserID = 0;
public function initUser($id) {
// get user details from database
$this->setUserID($id);
// etc...
}
private function setUserID($value) { $this->UserID = $value; }
public function getUserID() { return $this->UserID; }
}
common.php:
if(unset($clsUser)) $clsUser = new clsSetUser;
login-exec.php:
$clsUser->initUser($id);
header("Location: somewhere.php");
somewhere.php:
echo $clsUser->getUserID();
// here it equals 0
any ideas? does "header" serialize everything?
This is because PHP is actually starting from a clean slate in somewhere.php.
header("Location: somewhere.php"); sends a command the browser to connect to a different page. In this page non of variables of the previous page are available in PHP.
You need to set the userId in the $_SESSION so that you can reload the user from the database when he visits somewhere.php.
login-exec.php
$clsUser->initUser($id);
$_SESSION['user_id'] = $id;
header("Location: somewhere.php");
somewhere.php
$clsUser->initUser($_SESSION['user_id']);
EDIT: 4
I went and tried this out with teh regular session handler, same issue could it be some OS error?
session_start();
$_SESSION['h0']=5;
session_regenerate_id(true);
Again when reloading the page multiple times you get A LOT sessions all with the same data.
For some reason when executing this script the
define('endl', "<br>");
$session->start_session();
echo session_id().endl;
session_regenerate_id(true);
echo session_id().endl;
On the top part I'm using delete_old_session
session_regenerate_id(true)
bool session_regenerate_id ([ bool $delete_old_session = false ] )
So the expected behavior is to generate a new session and then delete the old one
if I execute it normally I have the right behavior...
output:
d5ips18ji4rg7q63skuf7955b4
udk903d5o2nbeoq5soujng0bp5
http://s7.postimg.org/67dbyv3x7/image.png
But if I reload the page multiple times, (keep f5 pressed for a couple o seconds...)
it created over 60 sessions
http://s7.postimg.org/442wr744b/image.png
I dont know if Im implementing this correctly...
EDIT 2:
Destroy callback
public function destroy($sessionId) {
$qry = "DELETE FROM sessions WHERE id = :id";
if (!isset($this->dStatement)) {
$this->dStatement = $this->pdo->prepare($qry);
}
$this->dStatement->bindParam(':id', $sessionId, PDO::PARAM_INT);
if ($this->dStatement->execute()) {
return true;
} else {
echo "error destroy()";
return false;
}
}
I've even tryied this methods insted of the regular sess_reg_id(true)
public function regen_id(){
$sessionId = session_id();
echo $sessionId;
$qry = "INSERT INTO sessiondeletequeue VALUES (:id, 0)";
if(!isset($this->regQuery)){
$this->regQuery = $this->pdo->prepare($qry);
}
$this->regQuery->bindParam(':id', $sessionId, PDO::PARAM_STR);
if($this->regQuery->execute()){
session_regenerate_id();
echo "<br>";
$this->forceDelete();
return true;
}
else{
return false;
}
}
private function forceDelete(){
$qry = "SELECT id FROM sessiondeletequeue";
foreach($this->pdo->query($qry) as $row){
$this->destroy($row['id']);
if(!isset($this->forceQuery)){
$this->forceQuery = $this->pdo->prepare("UPDATE sessiondeletequeue SET deleted = 1 WHERE id = :id");
}
$this->forceQuery->bindParam(':id', $row['id'], PDO::PARAM_STR);
$this->forceQuery->execute();
}
$this->pdo->query("DELETE FROM sessiondeletequeue WHERE deleted = 1 ");
EDIT 3:
I know I could find a way around it, but I'm curious to know why the heck is creating that many sessions!! D:
You're probably mixing up PHP's default session mechanism with your framework's or your own session implementation.
$session->start_session(); // where does $session come from?
//and then
session_id();
Yes, it's working the expected way. You're generating a new session ID on every page reload. So the newly generated session ID is being stored on the database.
Regenerate the session ID only when you need. You probably don't need it generated on every request to the page.