PHP Cannot delete this cookie if my life depended on it - php

I am creating a simple Logout script and my cookie ("is_logged_in"), for some reason, cannot be deleted, despite all of my efforts.
I have tried all of the following (+ lots more):
setcookie("is_logged_in");
setcookie("is_logged_in","");
setcookie("is_logged_in","",time()-3600);
setcookie("is_logged_in","",time()-3600,"\");
setcookie("is_logged_in",FALSE); # or NULL, 0, etc.
unset($_COOKIE["is_logged_in"]);
Here is my PHP code (and yes there is a session_start() but it just isn't included in this excerpt).
<?php
require_once $_SERVER["DOCUMENT_ROOT"]."/taxi/support/required_classes.php";
ob_start();
class Logout {
final public function __construct(){
$_SESSION = array();
if(isset($_COOKIE["is_logged_in"])) {
setcookie("is_logged_in","",time()-3600,"/");
} // end if
session_destroy();
header("location: ../pages/index.php");
} // end __construct
} // end class Logout
$_logout = new Logout();
ob_flush();
?>

Related

PHP Session Login Controller

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!

Replacement for Session['msg'] if I used session_start twice? Error: Session has already been started

I get an error above my students.php
A session had already been started - ignoring session_start() in ...
I have a CRUD wherein I have to notify user if the students have been updated, deleted or created.
The CRUD is working fine, however, if I remove session_start() in server.php, the notification wouldn't show.
students.php:
<?php if (isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
server.php
if(!isset($_SESSION))
{
session_start();
}
...
$_SESSION['msg'] = "New student saved";
header('location: students.php'); //redirect back to page
$_SESSION['msg'] = "Information updated";
header('location: students.php'); //redirect back to page
redirect.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
Should I just change the var $_SESSION['msg'] to another variable? I'm a total beginner in PHP, sorry if it might be a stupid question.
It doesn't look like you have a framework going, so I think there are some general tips to help your script succeed.
1) Have a top-level config file in your site root that you include at the top of all your MAIN pages:
/config.php
<?php
# Create some helpful constants
define('ROOT_DIR',__DIR__);
define('DS',DIRECTORY_SEPARATOR);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('BASE_URL','http://www.example.com');
# This includes our function loader (see below)
include_once(FUNCTIONS.DS.'loadFunc.php');
# Load the getSession() function (see below)
loadFunc('getSession');
# Start session here
session_start();
2) Then create some helpful functions (I would learn Object Oriented Programming instead so you can use a framework effectively, but functions are better than nothing):
/functions/loadFunc.php
function loadFunc($name)
{
if(!is_array($name))
$name = array($name);
foreach($name as $func) {
# If the function is already loaded, skip
if(function_exists($func))
continue;
# See if the function file exists
if(is_file($file = FUNCTIONS.DS.$func.'.php'))
include_once($file);
}
}
}
/functions/getSession.php
function getSession($key=false,$clear=false)
{
# If requesting a specific value return that
if(!empty($key)) {
# Get value
$value = (isset($_SESSION[$key]))? $_SESSON[$key] : false;
# If the key is set and clear is set, clear the value
if(isset($_SESSON[$key]) && $clear) {
unset($_SESSON[$key]);
}
# Return session value
return $value;
}
# No key set, return full session
return $_SESSION;
}
/functions/setSession.php
function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
/functions/redirect.php
function redirect($to,$exit=true)
{
header("Location: {$to}");
# You should exit on redirect
if($exit)
exit;
}
3) Now, when you go to create a page, you include this config ONCE at the top of the page:
/students.php
<?php
# Now that you include this, you know session is always set
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Get the key msg from the session and use parameter #2 to clear the session key
$msg = getSession('msg',true);
# It's not empty, write message
if($msg): ?>
<div class="msg">
<?php echo $msg ?>
</div>
<?php endif ?>
/server.php
<?php
# Include config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Load our two required functions
loadFunc(array('setSession','redirect'));
# You have to determine either message here, not both.
# Using pseudo-code here to demonstrate
if($add) {
# Use function to set session value
setSession('msg',"New student saved");
}
elseif($update) {
setSession('msg',"Information updated");
}
# Since both use the same redirect, you only need it once
redirect('students.php');
So, if you delete all your session_start() in all your files except for the config and then always include the config on the top-level page at the top, you won't run into errors for the session.

Session lost after form submit in wordpress

The session I set is lost after the form is submitted.
I had built the session class to set new session, unset and so on. In function.php of wordpress template.
function.php
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
Session.php
class session {
function __construct() {
}
function set_flashdata($name, $value) {
$_SESSION[$name] = $value;
}
function flashdata($name) {
if (isset($_SESSION[$name])) {
$str = $_SESSION[$name];
return $str;
} else {
return FALSE;
}
}
function userdata($name) {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
} else {
return FALSE;
}
}
function set_userdata($name, $value) {
$_SESSION[$name] = $value;
}
function unset_userdata($name) {
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
}
}
}
I try to set session as :
<?php
$sess = new session();
$sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
//input buttons
</form>
After submit the form it goes to the permalink(212). Then I tried.
<?php
$sess = new session();
$value = $sess->userdata('sess_name');
var_dump($value); //returns false. That means session is lost after form submit. Why?
?>
You need to move session start/resume into your Session's constructor.
Like so:
class session
{
function __construct()
{
if (! session_id()) {
session_start();
}
}
Another thing to mention, every time you'll do new Session you'll be getting an object of the same functionality working with same global variable $_SESSION.
You don't need more than one $session object, it would be a good time to look into Singleton pattern.
You have to call always session_start() for each request.
The mission of session_start() is:
Creates a new session
Restart an existing session
That means, if you have created a session, and you don't call to the method session_start(), the variable $_SESSION is not going to be fulfilled.
Except: If in your php.ini you have set the option session.auto_start to 1, then, in that case it is not needed to call the session_start() because the variable $_SESSION is fulfilled implicitly.
You need to use wordpress global variable for condition that session is set or not something like :
global $session;
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
It might be due to www. at the start of your website domain. Make sure that both of pages use the same structure.
Also I faced with the same issue long time ago when the form sends the data to a secured address (https://)
I hope these two items may help you.
Sounds to me like session_start() is not set at the start of the page that get_permalink(212;) refers to.
I have almost no experience with WP itself though, so I might misunderstand the functionality of get_permalink()
I agree with the answer from #rock3t to initialize session in constructor of class, but every time a class object is initiated, it will go to check for session!
Instead, if you are fine, the simplest way to get access to session is by adding following lines to your wp-config.php file before the call to wp-settings
if (!session_id())
session_start();
This will set/initialize session globally and you won't need to set/check for session_start in constructor of a class.
Thank you.

calling a php session variable from outer script

i have a problem calling a session variable from another script. can anybody help me on this matter.
Below is the script that i create the session and store the time in a session variable.
<?php
session_start();
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Here is the script that i try to access this session variable from a function of it. till now nothing worked
<?php
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
this hasnt worked upto now, nothing prints...can anybody give tips to sought this out and its compulsory to have this function timeofclick
You're not creating your class on your second file add:
//I don't know what this does but if it already starts a session remove the session start inside the class.
include '../../mydomain/myscript.php';
$survey = new survey_Tracksciprt();
$survey::timeofclick();
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
I also advice putting session_start at the top of your file.
<?php
session_start();
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
Always use the session_start(); at the top line of the page.
First, you need an init-session.php file, containing:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Second, you need to include this file at the start of your loader/layout (whatever you have there), so no operation will be executed before you initialize your session.
Third, you should initialize $orgtimestamp like this:
<?php
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Fourth, you need to call survey_Tracksciprt::timeofclick().

Sessions are stateful, PHP user code is not

After validating user input and storing login credentials I start a session by calling session::start and then reload the index.php file by calling general::reload. The I use session::is_start() to determine which page to load from the index file.
I don't think this is working correctly as I always get the same page loaded - b1e.htm.
My concern is that my static class session does not maintain its value between the AJAX/PHP call and the reload index.php call.
Similar posting - here
index.php
include 'b2.php';
if(session::is_start())
{
include 'b2e.htm'; // user is logged in
}
else
{
include 'b1e.htm'; // user is not logged it
}
Snippet - session:start() and session::is_start();
class session
{
protected static $ses_id ="";
public static function start()
{
self::$ses_id = session_start();
}
public static function is_start()
{
return self::$ses_id;
}
public static function finish()
{
self::$ses_id = 0;
$_SESSION=array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
{
setcookie(session_name(), '', time()-2592000, '/');
}
session_destroy();
}
}
Snippet - general::reload()
class general
{
public static function reload()
{
$uri = 'http://';
$uri .= $_SERVER['HTTP_HOST'];
header('Location: '.$uri.'/host_name');
}
You can encapsulate and consolidate session functionality, but you can not fully monitor sessions with a class as php user code is stateless (even when using static keyword)...i.e. it will depend upon SESSION to retain state.
You need to call your session_start(); to actually start the session on each page.

Categories