this is the script im using for a login function. But if i want to add a timer to the session, it ignores it. I have tried it on 10 seconds, or 1 minute. But it does not seem to work. Someone has an idea of what is going wrong?
this is the line of code im using for the timer : session_set_cookie_params(3600,"/");
Thanks in forehand.
public function login($username, $password) {
$salt="";
$this->user_id=0;
$this->status=0;
$salt_query=$this->mysqli->query(
<<<EOT
SELECT salt
FROM xxxxx
WHERE username="{$username}"
EOT
);
$salt_query = $salt_query->fetch_row();
$salt = $salt_query[0];
$hash = hash('sha512', $password.= $salt);
$result = $this->mysqli->query(
<<<EOT
SELECT werknemer_id,status
FROM xxxxx
WHERE username="{$username}" AND password="{$hash}"
EOT
);
$rij =$result->fetch_row();
if ((empty($rij)) || (empty($rij[0]))) return(1);// Invalid combination
if (($rij[1]<1) || ($rij[1]>2)){
return(2); // Inactive account
}
$this->user_id=intval($rij[0]);
$this->status=intval($rij[1]);
session_regenerate_id();
$_SESSION['werknemer_id']=$this->user_id;
session_set_cookie_params(3600,"/");
return(0); // login
}
From the manual. I havent used it but it does say that you have to use it in every script. Also, you have to do it before start_session. I think that on of these is your problem.
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.
Reference.
Related
I'd like to store a datetime variable into different tables by using two functions. I use constraint in CI but still have no luck.
This is the constraint:
$date_now = date("ymdhis");
define('TODAY_DATE',$date_now);
These are the functions:
public function save_activity_m(){
foreach($details as $rows){
$stock_in = $rows['product']."_".TODAY_DATE;
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
public function save_notifikasi(){
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran."_".TODAY_DATE;
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
How to make the datetime is the same for $data['STOCK_IN'] and $data['note_date']?
Since the web is stateless, no data in a PHP variable will be held from one page (or load) to another; essentially you're booting the application from scratch each time.
The only way around this is to use some sort of semi-persistent storage such as a cookie or session variable (or persistent storage like the database) - setting a constant, e.g. define('TODAY_DATE',$date_now); will only make that data constant for the current execution of the script(s).
This is a basic example using session storage ($_SESSION):
<?php
// crank up the session
// you may well have one running already,
// in which case ignore this
session_start();
// store the execution time for this script
// as a session variable if it's NOT already set
// i.e. don't overwrite it
if(empty($_SESSION['time_now'])) $_SESSION['time_now'] = date("ymdhis");
public function save_activity_m() {
foreach($details as $rows) {
$stock_in = $rows['product'] . "_" . $_SESSION['time_now'];
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
/**
* Assuming this is the last thing you want to
* do with 'time_now' you should unset it here
*/
public function save_notifikasi() {
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran . "_" . $_SESSION['time_now'];
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
// since we're done with the 'time_now' session
// variable we need to unset it...
unset($_SESSION['time_now']);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
// just to be on the safe side unset the 'time_now' session var
// if it's older than 1 minute - otherwise future calls to this
// script, by the same user, during the same session will use
// the stored value from $_SESSION['time_now']
if(isset($_SESSION['time_now'])) {
$sessionTime = DateTime::createFromFormat('ymdhis', $_SESSION['time_now']);
$oneMinuteAgoTime = new DateTime('-1 minute');
if($sessionTime < $oneMinuteAgoTime) {
unset($_SESSION['time_now']);
}
}
The caveat is that because you've stored the time in a session variable, unless you update or unset it, it will always be there (for the current session) - so if the user runs the script again it'll just use the stored time from the session.
I've put in a couple of unset() calls to try and work around this.
See PHP: define. It's a constant and it should have the same value if the two functions executed in the same time the script is running.
I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");
I am using Zend framework 1 and I need to change the session id at runtime with a predefined prefix, however I am getting the following error "The session has already been started. The session id must be set first." The issue is that the session state still remains started even after calling the destroy and writeclose. I also tried using the php methods unset & destroy but still same issue.
$oldSession = new Zend_Session_Namespace();
Zend_Session::destroy();
Zend_Session::writeClose();
$sessId = "dskjfghdsjfhsdkf"; //Random hash
Zend_Session::setId("myprefix".$sessId);
$newSession = new Zend_Session_Namespace();
foreach($oldSession as $idx => $data){
$newSession->$idx = $data;
}
Looks like it is not possible,
Snippet from Zend_Session.php:
if (!self::$_unitTestEnabled && defined('SID')) {
/** #see Zend_Session_Exception */
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception('The session has already been started. The session id must be set first.');
}
Though after reading explanations about setting cookie and not working for first time i find it difficult to resolve the below problem as am new to php and cookies.
I have a webpage with for (e.g) cp.php, login.php, header.php, maindata.php , bottom.php. Whenever i login to the webpage cp.php will be processed from there 1.header.php will be called first 2.maindata.php will be called and 3.bottom.php will be called.
So am setting my cookie at maindata.php and the code is like,
<?php
$cid = $_GET["id"];
$XmlPath = $_GET["path"];
$numpath = $_GET["numpath"];
$finepath =$_GET["finepath"];
$Tech =$_GET["tech"];
$read_str="";
function read($Path)
{
$temp="";
if(file_exists($Path))
{
$library = new SimpleXMLElement($Path,null,true);
foreach($library->children("SAS") as $info){
foreach($info->children("SAS") as $attributes){
$nameVal = $attributes->Name."=".$attributes->Value;
$str_temp .=$nameVal."#";
}
}
}else
{
$str_temp ="NA";
}
return $str_temp;
}
$arrpath =explode(",",$XmlPath);
/*Reading and storing arrpath[0] has the path of xml to be parsed*/
$strG=read($arrpath[0]);
$strC=read($arrpath[1]);
$strB =read($arrpath[2]);
setcookie($cid.'strE',$strG);
setcookie($cid.'comstr',$strC);
setcookie($cid.'basstr',$strB);
(....)
in the same file am reading the cookie using the below code,
$read_str =$_COOKIE[$cid.'strE'].$_COOKIE[$cid.'comstr'].$_COOKIE[$cid.'basstr'];
after this process is done bottom.php will be called and for the first time loading is completed.As i said for the first time am not getting any value in $read_str, but if i refresh the page and do all the process again i am getting the value.
As SETCOOKIE will return TRUE incase of successfully setting cookie i tried putting it in an if-loop and it returned false even for the first time.
kindly assist me in finding where the problem exists!
Make use of isset to check if a cookie exists and then try setting one.
Something like this.
if(!isset($_COOKIE['yourcookie'])) {
setcookie('yourcookie', 'Some data !');
$_COOKIE['yourcookie'] = 'Some data !';
}
echo $_COOKIE['yourcookie'];
I arrived here looking for an answer as well. Here's the deal.
When you set a cookie it can only be accessed on the next page load, that is why you can't access it after you set it. If you really need to work with the cookie data right away, you could set the value directly in global cookie such as:
$_COOKIE['my_cookie'] = 'i am a cookie';
Use setcookie()just the same so you can set expiration, domain, etc..
I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");