I'm implementing a 'cookie notification bar' on my website. It's a grey transparent bar
that's fixed to the bottom of the screen with the notification of the use of cookies, a
link to a page with more info and on the far right a 'close' button. The bar hides
using a display:none with a javascript on-click event. My next problem: is it possible to set a cookie within the same function that closes the bar on-click? For it doesn't seem to be working, my code:
// Just before my body tag I have:
<script language="javascript">
function closeCookieBar() {
document.getElementById('cookiepolicy').style.display = 'none';
SetCookie("cookiepolicy", 1, 8)
}
</script>
// At the bottom of the page I have:
<div id="cookiepolicy" <?php if(isset($_cookie['cookiepolicy'])){ echo "style=\"display:none\""; } ?> >
<div id="cookiepolicy-wrapper">
<div id="cookiepolicy-txt">
<span id="cookiepolicy-notice">Deze website maakt gebruik van cookies. Waarom? Klik hier voor meer informatie.</span>
<span id="cookiepolicy-accept-cookies" onclick="closeCookieBar();">Sluit</span>
</div>
</div>
</div>
Next issue I am forseeing: I have about 415 subdomains I want this cookie to be saved for as well, if it set on the main domain, will it work for my subdomains?
Thanks in advance!
Sander
I may be able to help with part of this. Since you're using PHP, this PHP script can set a cookie that is available to all subdomains and subdirectories. If you're using a domain like xxx.co.uk you may need some adjustment around lines 30-40.
<?php // RAY_cookie_splash_page.php
error_reporting(E_ALL);
// SHOW A SPLASH PAGE ON FIRST ENTRY, THEN COOKIE THE BROWSER TO SKIP SPLASH PAGE
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES
// MAN PAGE: http://php.net/manual/en/function.setcookie.php
// DEFINITIONS AS NEEDED HERE
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )
// CONSTRUCT AND SET THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
$cookie_expires = 0;
// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
$cookie_expires = time() + date('Z') + COOKIE_LIFE;
// CHOOSE THE COOKIE NAME AND VALUE
$cookie_name = 'Fred';
$cookie_value = 'Wilma';
// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
$cookie_path = '/';
// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
$x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
$y = count($x);
if ($y == 1) // MAYBE 'localhost'?
{
$cookie_domain = $x[0];
} else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
{
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
$cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
}
// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
$cookie_secure = FALSE;
// HIDE COOKIE FROM JAVASCRIPT TO IMPROVE SECURITY (PHP 5.2+)
$cookie_http = TRUE;
// SET THE COOKIE (BUT DO NOT BOTHER OUTPUTTING THE DEBUGGING MESSAGES)
if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
{
// echo "<br/>SUCCESS! THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
} else {
// echo "<br/>FAILURE! THE COOKIE WAS NOT SET AS EXPECTED \n";
}
// IF THE COOKIE IS NOT AVAILABLE IN THIS SCRIPT, SHOW THE SPLASH PAGE
if (empty($_COOKIE["Fred"]))
{
echo "<h1>SPLASH PAGE</h1>\n";
echo "<p>CONTINUE TO SITE</p>\n";
echo date('c');
die("\nSPLASH COMPLETE");
}
// SPLASH PAGE HAS ALREADY BEEN SHOWN
echo "<h1>REGULAR START PAGE - AFTER SPLASH HAS BEEN SHOWN</h1>\n";
echo "<p>CONTINUE TO SITE</p>\n";
echo date('c');
die("\nREGULAR PAGE COMPLETE");
You can create your cookie in js and use it in PHP like this
function closeCookieBar() {
document.getElementById('cookiepolicy').style.display = 'none';
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = name+"="+value+expires+"; path=/; domain=.example.com";
}
<div id="cookiepolicy" <?php if(isset($_cookie['cookiepolicy'])){ echo "style=\"display:none\""; } ?> >
In place of name put name of your cookie and in domain put your domain.
Hope it helps...
For more u may visit Set cookie wih JS, read with PHP problem
Related
I am maintaining the code for an eCommerce website, they use a highly modified version of osCommerce v2.2 RC2. Was noticing an issue where the session isn't started for a new user until they visit the 2nd page of the site.
Looking at the code, before starting the session, it tries to set a cookie. If it detects the cookie it starts the session. Something along this line:
setcookie('cookie_test', 'please_accept_for_session', time()+60*60*24*30, $cookie_path, $cookie_domain);
if (isset($_COOKIE['cookie_test'])) {
session_start();
...
I found an article here that talks about a situation like this, it states:
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Which explains why it takes two page loads for the session to be started. One to set the cookie and one to get notification from the browser that the cookie is set.
My question is, is there anyway around having to go through two page loads to detect the cookie was successfully set on the users browser?
I found this question that didn't really answer my question completely. The highest voted solution was:
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
Which may make it "work" but it doesn't truely tell me that the script was able to set a cookie successfully.
I also found this question, that suggested accessing the headers_list to find the cookie information like so:
function getcookie($name) {
$cookies = [];
$headers = headers_list();
// see http://tools.ietf.org/html/rfc6265#section-4.1.1
foreach($headers as $header) {
if (strpos($header, 'Set-Cookie: ') === 0) {
$value = str_replace('&', urlencode('&'), substr($header, 12));
parse_str(current(explode(';', $value, 1)), $pair);
$cookies = array_merge_recursive($cookies, $pair);
}
}
return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');
Which, again, doesn't seem to be verifying that the cookie was set successfully. All this appears to do is search the headers being sent to the browser for the cookie value.
The only solution I can think of is to redirect on the first visit after setting the cookie. Is there any other way?
Here is the answer:
<?php
function set_cookie($name, $value) {
if (!isset($_COOKIE[$name]) || ($_COOKIE[$name] != $value)) {
$_COOKIE[$name] = $value;
}
setcookie($name, $value, strtotime('+1 week'), '/');
}
// Usage:
set_cookie('username', 'ABC'); //Modify the value to see the change
echo $_COOKIE['username'];
I have a simple website where you need only a password to access the contents. Then there are 3 fields where user inputs data, which are then stored in cookies. In the end - there is a logout script that resets the session and unsets cookies.
Please find the relevant code below:
Login page (index)
<?php
session_start();
$password = '';
$wrongPassword = '';
if (isset($_POST['sub'])) {
$password = $_POST['login_passcode'];
if ($password === 'PASSCODE') {
$_SESSION['login'] = true;
header('LOCATION:/personal.php');
die();
} else {
$wrongPassword = true;
}
}
if (isset($_COOKIE['m_username'])) {
header('LOCATION:/personal.php');
die();
}
?>
The page with contents, where user inputs name, department and start date
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header("Location:/index.php");
die();
}
?>
and the logout script:
<?PHP
session_start();
if (isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_username'])):
setcookie('marriott_username', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_startdate'])):
setcookie('marriott_startdate', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_department'])):
setcookie('m_department', '', time() - 7000000,'/');
endif;
$_SESSION = array();
session_destroy();
header ("Location:/index.php");
die();
?>
jQuery to create cookies below:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Cookies do expire (at least on chrome), however after trying to access website after a few hours or days, I get the error about too many redirections. I believe this might be due to some differences between session expiration time and cookies expiration time (5 days for cookies), but I don't really know where to start fixing these...
Also, on Internet Explorer (IE8) the redirects problem occurs even when I go through logout directly.
Will be grateful for any help,
E.
You are correct in thinking different cookie expirations are behind the too many redirects problem.
If isset($_COOKIE['m_username']) is true in the index page, then you are redirected to the personal page, in which if if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) is also true, it sends you back to the index, therefore creating a loop. This would be caused by the session cookie expiring before the cookies you set.
The $_COOKIE and $_SESSION superglobals refer to two different sets of cookies. One solution is to use just the PHP session and store all your session data in the $_SESSION superglobal.
For example:
$_SESSION['m_username'] = 'whatever_value';
This will however generate an overhead in extra memory usage. If you still want to use your own cookies then just make sure any logic determining redirects is based on the session, not the presence of cookies you set.
For example:
// When logging in
$_SESSION['logged_in'] = true;
// On every page that requires login
if(!$_SESSION['logged_in']) // Redirect
My web structure is
Header-of-page
Nav Link || iFrame
Footer
I'm Trying to handle session timeout, when session has timeout I'm trying to redirect page to login page, this works fine(session timeout).
Problem:
When I'm redirecting the page,login page is displayed in iFrame, which is not expected.
How can I redirect to login page(whole window),rather than opeing it in iFrame.
I Tried:
1. using header
2. using javascript(Commented)
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
header("Location: login.php?msg=timeout");
// echo '<script language="javascript">';
// echo 'window.location.replace("login.php");';
// echo '</script>';
}
}
$_SESSION['timeout'] = time();
?>
Please guide me for this issue. Thanks!
Try this: window.top.location.href = "http://www.site.com";
As long as this is on the same domain name.
More here: Redirect parent window from an iframe action
use this one
in script window.parent.location='http://localhost/users/login.php'
or follow this link
https://forums.digitalpoint.com/threads/button-to-navigate-to-a-new-page-but-exit-the-iframe-too.1846291/
hope you will get solution.
create form with target="_parent" and action="login.php"
and submit using $(form).submit();
The problem here is than the iFrame is a another window in the partent window.
So when is begin redirected the iFrame only affect self (Not the parent or partents of the parent).
To don't use javascript we can put a link to login.php wich target the parent.
Goto login.php
_top will target the top window frame.
http://reference.sitepoint.com/html/a/target#target__li5 Read about target attribute set on _top.
The other method is using javascript:
window.top.location.assign("http://www.yoursite.com/login.php"); // Redirect
// window top frame to "http://yoursite.com/login.php"
Please read following links about javascript window documentation:
http://www.w3schools.com/jsref/prop_win_top.asp
http://www.w3schools.com/js/js_window_location.asp
In case yo want a "PHP" code, just use echo
http://www.php.net/manual/en/function.echo.php
I hope this mightly helps.
one of the probably mistakes,
if the encoding of this file is "UTF-8" it will create 2 hidden characters in the top of the file.
To fix this issue, try to change the encoding to "UTF-8 without BOM"
you can put a exit; after the redirect
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
header("Location: login.php?msg=timeout");
exit(); // LOOK AT THIS LINE
// echo '<script language="javascript">';
// echo 'window.location.replace("login.php");';
// echo '</script>';
}
}
$_SESSION['timeout'] = time();
?>
Try this way. Php redirection works before JS redirection so browser never runs JS.
which that's the only way you can redirect whole window object.
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
// header("Location: login.php?msg=timeout");
echo '<script language="javascript">window.top.location.href = "login.php?msg=timeout";</script>';
}
}
$_SESSION['timeout'] = time();
You would need to break the iframe. Try this..
if(this != top){
top.location.href = this.location.href;
}
OR (with doc reference)
if(this != top){
top.document.location.href = this.document.location.href;
}
Alternatively
this.top.location !== this.location && (this.top.location = this.location);
I am guessing this php being in the file running in the iframe in that case you have to instruct the parent window to redirect to login.
Echo the below code from php so when you page will render in browser, it will instruct the script to reload the page. But for the page not to load the rest of the page issue an exit(0). Your final script should look like below.
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
echo '<script language="javascript">';
//Echo the exact full url to your login page
echo 'window.parent.location="login.php?msg=timeout"';
echo '</script>';
exit(0); // So script won't go further displaying the page
}
}
$_SESSION['timeout'] = time();
?>
Hope that helps.
Check this solution out. I would put it before the header to prevent flickering. This way, your page will be prevented from swallowing itself.
http://usablelayout.com/articles/automatically-break-out-iframe
<script type="text/javascript">
<!--
if (top.location!= self.location) {
top.location = self.location.href
}
//-->
</script>
If you are using the login action on the same page, Header redirection will not work.
you can use simple the window.location.href='url';
For the login , you have to send the login query to new page, from there you can easily redirect easily...
Try this one
php
echo "<script> window.location='forgot.php'</script>";
html
<META HTTP-EQUIV="REFRESH" CONTENT="3;URL=http://google.com">
On every page I set a cookie to color the header button corresponding to that session.
The problem is that the first time I open a page in a different section, the cookie remains the old, and the colored button too.
Then if I click another time the same button, the cookie is correctly setted. Why?
Here my code:
<?php
include $_SERVER['PERCORSO_GLOBALS'];
$pagelevel = '1';
require_once ROOT_DIR.'/administrator/flock/session_users.php';
setcookie('lng', 'it');
?>
<head>
...
</head>
<body>
<?php
$currentpage = basename(__FILE__);
function colorButtonHeader($section){
if(isset($_COOKIE['lng'])){
if($_COOKIE['lng'] == $section){
echo "buttonon";
}
}else{
echo 'Error';
die($refresh);
}
}
?>
<div id="button">
<ul>
<li>HOME</span></li>
<li>ITALIANO</span></li>
<li>DEUTSCH</span></li>
<li>FRANÇAIS</span></li>
</ul>
</div>
?>
<div id="content">
...
</div>
</body>
</html>
Read the documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
When you use setcookie(), you're setting a cookie, but the $_COOKIE array contains only existing cookies (it's created on the page load).
Do this instead:
setcookie('lng', 'it');
$_COOKIE["lng"] = "it";
or simply redirect to a page itself (header("Location: ".$_SERVER["PHP_SELF"]);) when the cookie is set for the first time.
Just simply reload the page each time You set Your cookies.
setcookie("Cookiename", $value, time()+1800, "/", $_SERVER['SERVER_NAME'], FALSE, TRUE);
header('Location:'.$_SERVER['REQUEST_URI']);
Cookie is set in client machine so you cannot set and check simultaneously from server,use JavaScript instead.
you can use this js function Taken from this post
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function colorButtonHeader(selected){
if(readCookie('lng') == selected ){
alert('cookie is set ');
}else{
alert('Wrong language');
}
}
I find this solution, which seems to be the fastest to improve:
function colorButtonHeader($section){
if(isset($_COOKIE['lng'])){
if($_COOKIE['lng'] == $section){
echo "buttonon";
setcookie('lng', '', time()-3600);
}
}else{
header("Location: ".$_SERVER["REQUEST_URI"]);
// header("Location: ".$_SERVER["PHP_SELF"]);
}
}
Destroy the cookie each time after using it. So on every page load the cookie is not ready to use. This means the page reload, but only once because then the cookie is avaiable. It will be used and the destroied again.
EDIT
If you pass parameters through the URL, then when you use:
header("Location: ".$_SERVER["PHP_SELF"]);
those parameters are getting lost. So it's better to use:
header("Location: ".$_SERVER["REQUEST_URI"]);
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.