I'm having a problem with this really short piece of code which I cannot get to work.
Basically, I want to display two different messages, depending on whether the user is new or returning.
<?php
if(isset($_COOKIE['visit']) && ($_COOKIE['visit'] == "true"))
{
echo 'cookie set, welcome back';
}else{
echo 'cookie not set, welcome new user';
}
setcookie("visit", "true", time()+60*60*24*600);
?>
The problem is that the cookie is not being set. I don't know what is wrong, can anyone help me?
You need to move the setcookie into the condition:
<?php
if(isset($_COOKIE['visit']) && $_COOKIE['visit'] == "true"){
echo 'cookie set, welcome back';
}else{
echo 'cookie not set, welcome new user';
setcookie("visit", "true", time()+60*60*24*600);
}
?>
If its not working then you should check the cookie is being sent back to the script. eg your browser or some browser addon interfering.
Be aware there is a new law that if your server is based in the EU, it requires you to obtain informed consent from your visitors before you can store or retrieve any information on there computer. http://www.cookielaw.org/
I had used the above code to make a modal window show only once.
The problem with the above is I was trying to use it at the end of a index page you can only use setcookie at the point where headers are set.
Instead I used:
if(isset($_COOKIE['visit']) && $_COOKIE['visit'] == "true"){
$load = false;
} else {
$load = true;
setcookie("visit", "true", time()+60*60*24*600);
}
That sets the cookie at the top of my PHP file if its not set then I use
if($load == true){
//do code on first run
}
where I needed to add code for the single run, I used it in the head to set a css style sheet for the one time use and in the footer to set some script / html for the one time use.
Related
first off all my English is not very good. Sorry I do my best. I am developing a CMS system. I need an inlog system for it. If you are not logged in you can't view some of the pages. I created a php session of it but it doesn't work on the other pages... I will include some off the code I wrote.
On the page I check the username and password, I created the session like this. And worked with session to check username and password, so it works on that page.
<?php
session_start();
$_SESSSION['gebruikersnaam'] = $_POST['gebruikersnaam'];
$_SESSSION['wachtwoord'] = $_POST['wachtwoord'];
if(($_SESSSION['gebruikersnaam'] == 'admin')
&& ($_SESSSION['wachtwoord'] == 'admin123')) {
include("adminpanel.php");
} else {
echo "Uw gebruikersnaam of wachtwoord is foutief.";
}
?>
On my other pages I added this to check if the user is logged in. I seem to never get that I am logged in and I can't echo the session out. Here is the code!
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
If the conditional statement with the session works, I can redirect the user to the log in page if he is not logged in.
Thanks in advance you would help me a lot!
That's because of a slip of the tongue, its $_SESSION not $_SESSSION and also:
$_SESSION['gebruikersnaam']['wachtwoord'];
Is actually referring to 1 value, not two:
$data = array('gebruikersnaam' => array('wachtwoord' => 'mijnwachtwoord'));
echo $data['gebruikersnaam']['wachtwoord'];
Instead do:
if(!empty($_SESSION['gebruikersnaam']) || !empty($_SESSION['wachtwoord'])){
echo "not ingelogd";
}
However, you should only store a username and id in a session. Storing the password is a potential security breach and is not necessary.
You could also use something like this to scan for required values:
function required_session_fields(array $keys){
foreach($keys as $k){
if(!array_key_exists($k, $_SESSION) && empty($_SESSION[$k])){
return false;
}
}
return true;
}
if(required_session_fields(['gebruikersnaam', 'wachtwoord'])){
echo 'gelukt';
}
If you started the session and included a file, you can still access the $_SESSION variable. On every new server request, make sure the session is started.
On the other pages you must have
session_start();
before
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
However this variable $_SESSION['gebruikersnaam']['wachtwoord'] is never created. Currently you have created $_SESSION['gebruikersnaam'] and $_SESSION['wachtwoord']
Perhaps you meant to have something like
if(!empty($_SESSION['gebruikersnaam']) && !empty($_SESSION['wachtwoord'])) {
echo "not ingelogd";
}
My latest idea which didn't seem to work was to store the array in a session,
include_once "scripts.php"
.........
//some code later
$errorlog .= "a random message<br/>";
$_SESSION['errorlog']=$errorlog;
reloadPage();
And then if 'errorlog' wasn't empty then display it,
[code]
<div class="randomclass">
<?php
displayErrors('errorlog');
?>
</div>
//here are the functions
function reloadPage(){
Header('Location: '.$_SERVER['PHP_SELF']);
}
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
[/code]
scripts.php
<?php
if(!isset($_SESSION)) session_start();
........
I have included scripts.php which starts with if(!isset($_SESSION)) session_start();.
I'm new to php, still making my first webpage (or actually, preparing scripts for it). I can't seem to successfully find bugs in my scripts because I don't know how to show the errors after a page reload is needed.
What I want, is a way to store strings like in this $errorlog and display it just like an echo(in div or whatever) after the page was reloaded
I don't get any errors with headers, the page reloads correctly but the problem is that no text is displayed after the page reloads, so I don't see why I shouldn't be using them unless you know another way to reload the page after script is done
surely this way is not the best one, but I think that the problem is very easy..
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){ // here you must put a variable $valuename instead a simple string 'valuename'
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
You must change the session key at this row whit: $_SESSION[$valuename]
if(!empty($_SESSION['valuename'])){
The correct function is the follow:
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION[$valuename])){
echo $_SESSION[$valuename];
unset($_SESSION[$valuename]);
return true;
}else{
return false;
}
}
Bye!
Marco
I'm sorry to trouble you, I have tried my best to solve this but I am not sure where I am going wrong and I was wondering if someone out there would be willing to help!
Basically, I am having some issues with $_SESSION variables; I would like for each occasion that a visitor came to the page that they would be shown a different content message.. The below code, when first landing on a page will seem to skip the first "content1", and will display "content2" instead, then "content3" after another revisit. I've put in an unset call, which eventually sends it there, am I not using _SESSIONS correctly?
I'm not sure how the session variable was assigned to 1, for it to land correctly in the if===1 statement without it first returning the original "content1"
if (empty($_SESSION)) {
session_start();
}
if (!isset($_SESSION['content'])) {
$content = "content1";
$_SESSION['content'] = 1;
return $content;
}
elseif ($_SESSION['content'] === 1) {
$content = "content2";
$_SESSION['content'] = 2;
return $content;
}
elseif($_SESSION['content'] === 2) {
$content = "content3";
unset($_SESSION['content']);
return $content;
}
Apologies for babbling or whether this was a simple fix / misunderstanding on my part. It's caused quite a headache!
Many thanks.
-edit-
This is a function that is called from within the same class, it has not gone through a loop anywhere either..
You are only calling session_start(); if the session has not been created.
What about the other times, when it's 1, or 2?
Call session_start(); regardless of your if (empty($_SESSION)) { statement
You should always use the session_start() function. If a session exists, it will continue it, otherwise it will create a new session.
Your code can then be simplified to the following:
// Start/Resume session
session_start();
// Get content
function display_message()
{
if ( ! isset($_SESSION['content']))
{
$_SESSION['content'] = 1;
}
if ($_SESSION['content'] == 1)
{
++$_SESSION['content']; // Increment session value
return 'Content #1';
}
elseif ($_SESSION['content'] == 2)
{
++$_SESSION['content']; // Increment session value
return 'Content #2';
}
elseif ($_SESSION['content'] == 3)
{
unset($_SESSION['content']); // Remove session value
return 'Content #3';
}
}
// Display content
echo display_message();
However, if someone visits your page a fourth time, they will be shown the first message again (because the session value is no longer tracking what they've been shown).
Perhaps this sort of functionality might be handled better with by using a cookie to track this information?
I've built a mobile detection with Mobile_Detect.php and it works great. Now if a User does not want to stay on the mobile site he can click on "Desktop-Version" and goes back to the main page via a 'mobile_off.php' which sets $_SESSION['mobile'] = 'off'.
The main Site executes the following code:
<?php
session_start();
// Did the User come back from mobile.php?
if ($_SESSION['mobile'] != 'off') {
include 'Mobile_Detect/Mobile_Detect.php';
$detect = new Mobile_Detect();
// Smartphone?
if ($detect->isMobile() && !$detect->isTablet()) {
// Redirection --> echo 'JS'
echo "<script>window.location='mobile.php'</script>";
}
}
?>
The Problem seems to be that if ($_SESSION['mobile'] != 'off') is ignored or wrong. My iPhone always sends me straight back to 'mobile.php'.
Can anyone help?
Perhaps I should show you the code from 'mobile_off.php':
<?php
session_start();
$_SESSION['mobile'] = 'off';
?>
You need to first check the session variable exists or not before checking the value of session variable.
For checking if session variable is set or not try this code
if(isset($_SESSION['mobile'])
After that check the value of session variable
This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.