When I open my website on localhost on chrome or other browser it set cookie until I close my browser. When I close my Chrome or other browser it delete my cookie even I have specified expiry time also. But it not lost on fire-fox, in fire-fox cookie is working properly even after closing browser. Why chrome and other browser delete my cookie after closing browser.
the code I have used :
setcookie( "CookieName", "Cookievalue", time() + 3600, "/");
Hello and Welcome Lucky Jaiswal, Please first off check whether chrome clears all cookies on exit. You can do this by going to settings then to privacy and security and then click on cookies and site data, there will be a toggle button saying clear all cookies and site data on exit please check if it is toggled on if yes please toggle it off and try your code again. If the problem still persists I shall try to give you another solution.
(Edit_2) Try this:
<?php
if ( isset($_COOKIE['test']) ) {
echo 'Cookie exists';
} else {
echo 'Cookie not found';
}
if (isset($_POST['login'])) {
if ( $_POST['name'] /* Add your extra conditions for example $_POST['name'] && $_POST['email'] && $_POST['password'] something like that*/ ) {
print_r($_POST);
session_start();
ob_start();
$name = $_POST['name'] ?? '';
$conn = mysqli_connect("localhost", "root", "", "trial") ;
$query = "SELECT * FROM `trialtable` WHERE `name` = '".mysqli_real_escape_string($conn, $name)."'";
$result = mysqli_query($conn, $query) or die("Error 3");
$row = mysqli_fetch_assoc($result);
if ($name == $row['name']) {
setcookie("test", '"'.$row['id'].'"', time() + 3600, "/");
}
mysqli_close($conn);
}
}
?>
P.S: Tested in Chrome, Microsoft Edge and Firefox!
Related
i'm implementing session, cookie simple from with a remember me check box . i want to use the cookie so the user could see index.php(protected content) i closed the browser to end the session to check if the cookie working and i got the famous error ..redirected you too many . i searched a bit but still stuck so what should i do? and Is what is the best practice to for doing it?
authentication.php
if(mysqli_num_rows($rows) > 0){
$chck_pass = password_verify($clean_password,$user_arr["password"]);
if($chck_pass){
//log in the user
$_SESSION["id"] =$user_arr["id"];
$_SESSION["fristname"] = $user_arr["fristname"];
$_SESSION["email"] = $user_arr["email"];
$_SESSION["verified"]=$user_arr["verified"];
$_SESSION["message"]="Please verify Your Email to Complete Registration";
//make login-id cookie
if(isset($_POST["remmberme"])){
$user=$user_arr['id'];
setcookie("I_user",$user, time() + 1800);
}
header("location:index.php");
exit();
}else{
$errors["login_error"]="Wrong Password";}
}else{
$errors["login_error"]="Wrong Email";
index.php
<?php
include("Authentication.php");
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
header("location:login.php");
}
?>
login.php
<?php
require_once("config/db_connect.php");
require("Authentication.php");
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
header("location:index.php");}
So you login, close your browser. Then open it up again.
You go to index.php and the following line runs
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
$_SESSION["id"] isn't set, so you redirect to login.php.
On login.php
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
$_COOKIE['I_user'] is set, so you redirect to index.php
Repeat forever.
Bear with me. Over the years I've begun to understand that I'm terrible at explaining myself.
I have a site with a page full of Spotify download links. On their first visit, people need to fill out a contact form to capture their email before being able to download. After that, they can download as many playlists as they want, forever.
When they click on the link the first time, a popup window opens the form.
After filling it out, the form redirects them to a new URL that sets the cookie (../playlists-for-events/?download=true). It also sets a variable so that the page doesn't need to be reloaded to download.
Now that the cookie is set, the playlists can be downloaded on any visit to the page (../playlists-for-events).
The cookie is setting as it's supposed to, but the PHP I've written isn't working.
The cookie
<?php $cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if(isset($_GET['download']) && $_GET['download'] == 'true'){
setcookie($cookie_name, $cookie_value, $date_of_expiry, '/',null,false,true);
$_COOKIE['spotify-download'] = 'allow';
} ?>
And the PHP that basically says "if the cookie isn't set, open the popup, else, start the download"
<?php if(!isset($_COOKIE['spotify-download'])) { ?>
<script type="text/javascript">function zforms_open_window(...)></script><a></a>
<?php } else { ?>
<?php } ?>
Help?
I've tested your code and it works fine, but the cookie can not be read until it is set. i.e. User redirected to /?download=true to set the cookie, it then needs to reload the page or go somewhere else that can now read the cookie.
<?php
$cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if( isset( $_GET['download'] ) && $_GET['download'] === 'true' ){
setcookie($cookie_name, $cookie_value, $date_of_expiry);
$_COOKIE[$cookie_name] = $cookie_value;
}
if( isset( $_COOKIE[$cookie_name] ) && $_COOKIE[$cookie_name] === $cookie_value) {
echo "You have access!";
} else {
echo "Access denied.";
}
I am trying to detect if a user on my page has cookies enabled or not. The following code performs the check, but, I have no idea on how to redirect the user to the page they came from.
The script starts a session and checks if it has already checked for cookies. If not, it redirects the user to a test page, and since I had called session_start() in the first page, I should see the PHPSESSID cookie if the user agent has cookies enabled.
The problem is, ths script might be called from any page of my site, and I will have to redirect them back to their selected page, say index.php?page=news&postid=4.
session_start();
// Check if client accepts cookies //
if (!isset($_SESSION['cookies_ok'])) {
if (isset($_GET['cookie_test'])) {
if (!isset($_COOKIE['PHPSESSID'])) {
die('Cookies are disabled');
} else {
$_SESSION['cookies_ok'] = true;
header(-------- - ? ? ? ? ? -------- -);
exit();
}
}
if (!isset($_COOKIE['PHPSESSID'])) {
header('Location: index.php?cookie_test=1');
exit();
}
}
I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.
Create two files, cookiechecker.php and stat.php
// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");
and
stat.php
<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'):
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else: // show the message ?>
cookie is not working
<? endif; ?>
Load cookiechecker.php in browser it'll tell cookie is working. Call it with command line like curl. It'll say, cookie is not working
Update
Here is a single file solution.
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
HTTP_REFERER did not work for me, seems like REQUEST_URI is what I need.
Here is the code I finally used:
session_start();
// ------------------------------- //
// Check if client accepts cookies //
// ------------------------------- //
if( !isset( $_SESSION['cookies_ok'] ) ) {
if( isset( $_GET['cookie_test'] ) ) {
if( !isset( $_COOKIE['PHPSESSID'] ) ) {
die('Cookies are disabled');
}
else {
$_SESSION['cookies_ok'] = true;
$go_to = $_SESSION['cookie_test_caller'];
unset( $_SESSION['cookie_test_caller'] );
header("Location: $go_to");
exit();
}
}
if( !isset( $_COOKIE['PHPSESSID'] ) ){
$_SESSION['cookie_test_caller'] = $_SERVER['REQUEST_URI'];
header('Location: index.php?cookie_test=1');
exit();
}
}
// ------------------------------- //
There's no need to save the original URL and redirect to it afterwards. You can perform a transparent redirect via AJAX which doesn't trigger a page reload. It's very simple to implement. You can check my post here: https://stackoverflow.com/a/18832817/2784322
I think this is easiest solution. Doesn't require separate files and allows you to proceed with script if cookies are enabled:
$cookiesEnabled = true;
if (!isset($_COOKIE['mycookie'])) {
$cookiesEnabled = false;
if (!isset($_GET['cookie_test'])) {
setcookie('mycookie', 1, 0, '/');
#ob_end_clean();
$_SESSION['original_url'] = $_SERVER['REQUEST_URI'];
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('?', $uri);
$q = (isset($uri[1]) && $uri[1])?explode('&', $uri[1]):array();
$q[] = 'cookie_test=1';
$uri[1] = implode('&', $q);
$uri = implode('?', $uri);
header('Location: '.$uri);
die;
}
} else if (isset($_GET['cookie_test'])) {
#ob_end_clean();
$uri = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header('Location: '.$uri);
die;
}
// if (!$cookiesEnabled) ... do what you want if cookies are disabled
PROBLEM
I've got an admin panel. Currently only Mozilla is able to process log ins. Browsers like Chrome, IE, Opera won't even show any message carried through sessions thus no one is able to log in any browser but Mozilla.
SOME INFORMATION
I'm using PHP 5.3.6 on my server, PHP 5.3.5 on my local
computer.
My code is Object Oriented.
ini_set("session.use_only_cookies", 1); and
ini_set('session.cookie_secure', 1); are used in construction method
of my session class.
This website on SLL
Login process: First I gather all information from form, validate and gather data. After validation if everything is right, I send this data to login method in my session class.
public function login ($user) {
global $siteSettings;
if ($user) {
$this->id = $_SESSION['id'] = $user->id;
$this->username = $_SESSION['username'] = $user->username;
$this->fullName = $_SESSION['fullName'] = $user->fullName;
$this->group_id = $_SESSION['group_id'] = $user->group_id;
$this->groupName = $_SESSION['groupName'] = $user->groupName;
$this->lastLogin = $_SESSION['lastLogin'] = $user->lastLogin;
$this->isAdmin = $_SESSION['isAdmin'] = ($user->admin == 1) ? true : false;
$this->isAgent = $_SESSION['isAgent'] = ($user->agent == 1) ? true : false;
self::$language = $_SESSION['language'] = ($user->language != "" || $user->language != NULL) ? $user->language : self::$language;
if ($user->language != "" || $user->language != NULL) {
$_SESSION['language'] = $user->language;
}else {
if (!defined(DEFAULT_LANGUAGE)) {
$browserLang = "|".$_SERVER["HTTP_ACCEPT_LANGUAGE"];
$browserLang = getStringBetween($browserLang, "|","-", FALSE);
if (!file_exists(LANGUAGES.$browserLang.".php")) $browserLang = FALSE;
}
$_SESSION['language'] = ($browserLang) ? $browserLang : DEFAULT_LANGUAGE;
}
# When 2 Update session_id
$date = new DateTime("now");
$UpdateTime = $siteSettings->session->timeOut * 60;
$date->add(new DateInterval("PT".$UpdateTime."S"));
$_SESSION['SIDUpdateTime'] = $date->format("Y-m-d G:i:s");
# UPDATE LAST LOGIN & ADD SESSION ID
# Clear Fields
members::clearFields();
members::$fields['id'] = $_SESSION['id'];
members::$fields['lastLogin'] = date("Y.m.d G:i:s");
members::$fields['lastLoginIP'] = $_SERVER['REMOTE_ADDR'];
# GET THE SALT
$saltInfo = members::getData("id", "salt", members::$fields['id']);
# SETTING SESSION ID ENCRYPTION
crypt::setKey($saltInfo->salt);
members::$fields['sessionID'] = crypt::encode(session_id());
members::$fields['sessionIP'] = $_SERVER['REMOTE_ADDR'];
members::$fields['sessionAgent'] = $_SERVER['HTTP_USER_AGENT'];
members::save();
$this->loggedIn = true;
var_dump($_SESSION);
}
}
When I dumb the data I can see $_SESSION got some values.
Just to test it, I stopped the script where after var_dump($_SESSION); (added die();) I created test.php file and tried this;
<?php
ob_start();
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '<pre>';
ob_end_flush();
?>
Output is array(0) {}
But when I try exactly the same thing with Mozilla, output of test.php is the way it should be (matching with login method's result in my session class).
I have tried from my local computer and I don't experience the same
problem.
I disabled all java script and jquery codes from the page just to
have no 'maybe' in my mind.
After dumping the data, script is stopped. That's why $_SESSION variable shouldn't change. For some reason when it is on the server only Mozilla is able to show expected result while other browsers shows NULL.
At this point I really don't know what to think of about this problem to try to solve it. All I can think of is, this problem is possibly related to server configuration. But then, PHP is server side programming. PHP shouldn't display different behavior for browsers like Jquery, CSS, HTML...
I'm sorry, I can't provide admin panel link. Considering this is an active admin panel. If necessary I could install it on another domain to let you try but I believe the information I gave above explains everything.
Thank you for your help in advance.
I had a similar problem... just enable the cookies.. so that after login the code to set the sessions will be executed and the sessions will be set. may be the sessions r not able to set...
also check this http://php.net/manual/en/function.session-cache-limiter.php
If something large doesn't work, trim it down, test & debug, and build up from there.
Does this work? (Run it twice).
<?php
session_start();
echo "Session ID: " . session_id() . "<br/>\n";
if (!isset($_SESSION['test']))
{
$_SESSION['test'] = "foobar";
echo "Setting session variable: ";
echo $_SESSION['test'];
}
else
{
echo "Restoring session variable: ";
echo $_SESSION['test'];
}
If this works in all browsers, it's got something to do with your code. An empty session might have something to do with a cookie that can't be written, for example. Also set error reporting to E_ALL | E_STRICT, so you'll see everything that goes wrong.
It turns out Mozilla FireFox is able to process some data but other browsers I tried with are not and therefore they reset the whole session with each page load.
I had no problem with my local computer but on the server I had sessions problem. I don't know why session_set_cookie_params(); and setcookie(); didn't work on the server so I had to code longer version;
private static function sessionLifeTime() {
global $siteSettings;
# HOW LONG WE WANT SESSIONS
$lifeTime = intval($siteSettings->session->timeOut) * 60;
if (isset($_SESSION['id']) && isset($_SESSION['lastActivity']) && (time() - $_SESSION['lastActivity'] > $lifeTime) ) {
// SEND INFORMATION TO USER
self::logout();
}
$_SESSION['lastActivity'] = time();
}
Replacing my method with the code above solved the problem.
Thank you all for your time, concern and interest.
Kind of a weird issue, ok here is my setup...
domain.com calls reads from an Iframe on sub.domain.com
sub.domain.com makes an ajax call to sub.domain.com/call.php
sub.domain.com returns ajax call to domain.com
AKA long-polling
Now, everything works perfectly when there is no session data (I close the browser and restart the page). However, once I reload the page and their is session data, call.php does a start_session() and hangs there.
I have tried almost everything and can't figure this out. I've tried destroying the session, unsetting all the session variables, modifying some ini settings, and nothing has worked.
Here is the code of call.php where the session data is...
session_start();
$sql = ("SELECT userid FROM status WHERE typing = '".mysql_real_escape_string($userid)."'");
$result = mysql_query($sql);
if ($result && mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$typing_id = $row['userid'];
if (!empty($typing_id)) {
if (isset($_SESSION['typing2'])) {
unset($_SESSION['typing2']);
}
} else {
$typing_id = "-1";
}
} else {
$typing_id = "-1";
if (isset($_SESSION['typing'])) {
unset($_SESSION['typing']);
}
}
if ($_SESSION['typing'] != $typing_id && !isset($_SESSION['typing2']) || $initialize == "1") {
$typing = array('typing_id' => $typing_id);
}
if ($typing_id == "-1") {
$_SESSION['typing2'] = "-1";
} else {
$_SESSION['typing'] = $typing_id;
}
Does anyone have any ideas? I was thinking it might have to do with the domain but I'm not sure.
Thanks!
I actually found out (after hours and hours of debugging and research) that the problem is being caused because the PHP session locks up. Then, when the new page loads, it won't work until the old session times out. A session_write_close() will fix it.
default session storage in php is cookie based. if you are using that you must set domain for your session cookie in php.ini
http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain