I have my code for setting the session like:
if($found>0){
session_start();
$_SESSION['user_name']=$user;
session_set_cookie_params(24*60*1,'/','.localhost');
$expire=time()+60*60*24;
setcookie("cookiename", $user, $expire);
header("location:http://localhost/UI/user/userprofile.php");
} else{
$message = "Username or password is not correct.";
header("Location:index.php?message={$message}");
}
here is my header content where i put login and logout
session_start();
if (isset($_COOKIE["cookiename"])){
$unm = $_SESSION["user_name"];
echo "User : " . $_SESSION["user_name"] . "";
echo " <a href='http://localhost/UI/user/logout.php'>logout</a>";
echo " <a class='addmeeting' href='http://localhost/UI/user/createmeeting.php' title='Create New Meeting'>Create Meeting</a>";
} else{
echo "<li><a href='register.php'>Register</a></li>";
echo " User : Guest!<br />";
}
My session is working for subfolder but it is not working for the parent folder.
Here is the directory structure:
UI
user
userprofile.php
login.php
logout.php
index.php
headers.php
Please tell me what i am doing wrong ?
My guess is that it's the cookie that's not working, rather than the session (your session code is inside an if() block that checks the cookie first).
Cookies default to being limited to the current folder, so it won't apply to the parent folders.
If you want it to apply to the whole site, you need to specify a / in the cookie, like so:
setcookie("cookiename", $user, $expire, '/');
This will set the cookie across your entire site, so your code should work.
However, I don't really understand why you're not just using sessions here anyway; why have cookies and sessions in the same context? You may as well set everything in the session and be done with it. (sessions are cookie based anyway)
Related
I just finished creating a website that includes a login page. When the user attempts to log in, I check the username and password against the database. If they both match, I start a session and set the session variables 'id' and 'uid', like so:
$sql = "SELECT * FROM users WHERE uidUsers = ? OR emailUsers = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header("Location: ../login.php?error=wrongpwd&mail=".$mailuid);
exit();
}
elseif($pwdCheck == true) {
session_start();
$_SESSION['id'] = $row['idUsers'];
$_SESSION['uid'] = $row['uidUsers'];
header("Location: ../login.php?login=success");
exit();
}
else {
header("Location: ../login.php?error=wrongpwd");
exit();
}
}
else {
header("Location: ../login.php?error=nouser&mail=".$mailuid);
exit();
}
}
In my header.php file, which is linked within every php page using include 'header.php';, I have php code that displays either log in/sign up buttons (if $_SESSION['id'] is not set) or a log out button (if $_SESSION['id'] is set). I also started a session in the header.php page. This is what the code of header.php looks like:
session_start();
if (isset($_SESSION['id'])) {
echo
"<div id='logout-form'>
<form action='includes/logout.inc.php' method='post'>
<button type='submit' name='logout-submit'>Log Out</button>
</form>
</div>";
}
else {
echo
"<div id='header-form'>
<form action='includes/login.inc.php' method='post'>
<button type='submit' name='login-button-header'>Log In</button>
</form>
<button id='signup-button'><a href='signup.php' class='header-signup'>Sign Up</a></button>
</div>";
}
if (isset($_SESSION['id'])) {
echo '<p class="greeting">Hello, <span class="greetingName">' . $_SESSION['uid'] . '</span></p>';
}
date_default_timezone_set("America/Los_Angeles");
Using xampp, I am connected to an apache server offline. When clicking through my site, the sessions work for every page; if I log in, it registers that I've logged in on every page I go to, as it should. However, when I posted my website a few days ago, it had trouble knowing if I was logged in or out. My website URL is writingboxco.com if you would like to see what I'm about to talk about. When I log in, it seems to know that I am logged in on every web page; I know this because it provides the message "Hello, [username]" on every page, which only happens when $_SESSION['id'] is set. However, when I click "Log Out" and go back to the home page, it still thinks that I'm logged on (because I probably am, but I don't know why). When the "Log Out" button is clicked, the script "logout.inc.php" runs. In this file, I unset and destroy the session variables, like so:
session_start();
session_unset();
session_destroy();
$_SESSION = [];
header("Location: ../login.php");
Additionally, I only stay logged in on some pages of the website. Some of them register that I've logged out, while other don't.
I'm not sure why I stay logged in after clicking the "Log Out" button, which should destroy the session variables. When my site is used offline, it works perfectly fine; when I log out, every page realizes it. However, when online, it doesn't work for every page. It only works for some (some pages stay logged in and some pages correctly log out). Additionally, when I try to log in with an alternate account, it signs me in, but on certain pages, the message "Hello [username]" still displays the username of the account I just logged out of instead of the account I just logged into. Any ideas on what the problem could be? Is it a problem with the failure to destroy the session variables? Could it be other code I should be looking at? Thanks.
UPDATE:
I found that there is an error message stating [28-Jan-2020 00:02:56 UTC] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home1/writipe3/public_html/searchUsers.php:1) in /home1/writipe3/public_html/header.php on line 5
on the error_log file. Any ideas why this would be happening?
When you're destroying a session in PHP you're not actually deleting it. You're merely marking it for garbage collection. The physical deletion happens later. So in order to ensure the session is actually destroyed you must also delete the session cookie, which propagate the session id.
If you look at Example #1 of the session_destory() documentation you'd see some sample code of how to go about doing this:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
Why is this behavior variable across platforms?
The reason you may see differences in how this atually works out in practice is because different platforms can use different methods of garbage collection for cleaning up session data. For example, on most Windows systems this might actually happen instantly. Some Debian-based (Ubuntu) systems are known to use an asynchronous GC method that happens outside of PHP.
PHP, by default, implements this via a probablistic algorithm wherein each request made to PHP will, within a given probability (usually about 1% of the time) will trigger the GC cycle. So the clean up is non-deterministic in almost all cases.
PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?
I'm pretty new to PHP and I'm struggling with my webshop.
I have a drop down menu on my site with one menu option containing all product categories in the webshop. As long as I'm navigating between these categories my session is persistent and working fine (I'm putting products in a shopping bag and I can move to the cart and go through with the whole order). But if I go to a page in another drop down menu option "outside" the webshop (like the contact page) my session is lost. I have used pretty much the same template to create these pages, but they are of course more simple with mostly text content (apart from the cart that is always accessible from the top menu).
The first page outside the webshop drop down menu option is ok with the correct session id, but when I move to the second page the session is gone. It doesn't matter in which order I visit the pages. The first one is always working but the following ones are not.
What on earth can be causing this behaviour? On every page I start with this piece of code:
<?php
session_start();
?>
<!DOCTYPE HTML>
...
Further down I include the cart in the top menu:
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/includes/right-cart.inc";
include_once($path);
And in the included cart code I use this line for the session id:
$currSession = session_id();
Any ideas?
EDIT 1:
I tried to add some error logging and noticed something interesting. I now start my files with this (just to find out some more information):
<?php
phpinfo();
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
// create session variable if it doesn't exist yet
if (isset($_SESSION['counter']))
$_SESSION['counter'] ++;
else
$_SESSION['counter'] = 1;
var_dump($_SESSION); echo "<br/>\n";
var_dump(session_id()); echo "<br/>\n";
var_dump(session_name()); echo "<br/>\n";
var_dump(session_get_cookie_params()); echo "<br/>\n";
?>
As long as I have the first row, phpinfo();, the session seems to be the same. But if I remove that line the session keeps renewing when refreshing the page...
EDIT 2
After a suggestion I tried to use a cookie to store a "session id" instead of a regular session. The code at the top of my page now seems like this:
<?php
session_start();
$currSession = "";
$cookie_name = "sessionId";
$cookie_value = "";
if(!isset($_COOKIE[$cookie_name])) {
$cookie_value = session_id();
setcookie( $cookie_name, $cookie_value, time() + (60*60*24*2), "/");
}
if(count($_COOKIE) > 0) {
$currSession = $_COOKIE[$cookie_name];
} else {
$currSession = session_id();
}
?>
But everytime I reload the page also the cookie value seems to change. I have tried different echo statements in the code to verify what happens but everything looks right (the cookie is created successfully, the isset function tells me that the cookie actually is set etc), but still the value in the cookie changes. Any ideas?
I finally solved the question so I thought I'll post the answer here in case someone else is having trouble.
I changed this line ("/"):
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), "/");
to ('/')
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), '/');
and suddenly it works! :-)
So problem is as the title says php session is being created for every page. So when I want to get a variable from session like this
session_start();
echo $_SESSION['error'];
It says "undefined index".
The problem is, in fact 'error' index defined but not in the current session since php creates new session for every page.
How can I solve this?
Note: I put session_start(); to every pages' first line, and before header("location:error.php") I put session_write_close(); and after the header there is die(); method too. I'm working on localhost. Using Latest version of WAMP and JETBRAINS PHPSTORM.
EDIT---------------------
This is where I define my session for error(this is from login.php page)
session_start();
$_SESSION['error'] = "Enter both username and password";
header('Location:error.php');
exit;
When the code above run, a session named "sess_amvrseubtusk0dpuo4fs35r0q1" is created and it has this line in it
error|s:32:"Enter both username and password";
And this is where I want to read session (this is from error.php page)
session_start();
echo 'SESSION: ' . $_SESSION['error'];
When the code above run, a session named "sess_m08lf25stbhg75gj2h0n0vose0" is created and it is empty.
I have all two of the created session files in my Session directory so 1 session file for each page.
EDIT 2----------------------------------
Here my php.ini file
http://pastebin.com/JNsPdzjH
EDIT 3----------------------------------
New php.ini file with changes "c:/wamp/tmp" to "C:/Users/nerzid/PhpstormProjects/Deneme/Session"
http://pastebin.com/Zaz37UPC
This posted as per your originally posted question should people wonder.
You may not have defined anything to $_SESSION['error'], least not with what you posted for code:
session_start();
echo $_SESSION['error'];
You would first need to assign something to it.
For example:
session_start();
$_SESSION['error'] = "Error.";
echo $_SESSION['error'];
Then on subsequent pages, you check if the session is set => isset() and/or empty => empty() or not.
I.e.:
if(isset($_SESSION['error']) && !empty($_SESSION['error'])){
echo $_SESSION['error'];
}
else{
echo "Session is not set";
// set a new one
}
If session is set from a variable example:
session_start();
$_SESSION['error'] = "Error.";
$error_x = $_SESSION['error'];
echo $error_x;
Also, when using header, add exit;
header("location:error.php")
exit;
always.
Sidenote:
Since you're working off of localhost, make sure the folder is writeable.
what I am trying to do is so simple but I can't find a clue on how to make it happen.
I have a huge form that is made of several php files and these files being called using AJAX that user has to fill, what exactly I want to achieve is:
1) test if session has expired on every page of this form.
2) if session is expired, I want to redirect him to a specific URL, let's say http://www.example.com
Thanks in advance for your help.
Regards.
You can check if the session is active by using
$session = JFactory::getSession();
if ($session->isActive()) {
}
First thing that comes to my mind is to check if session cookie exists.
If session is active then by default PHP session mechanism uses cookie with default name 'PHPSESSID'. So if cookie PHPSESSID exists, your session is active.
You can check if session cookie exists like this:
if(isset($_COOKIE['PHPSESSID'])) {
echo 'Session is active!';
} else {
echo 'Session is not active!';
}
To redirect you can use this:
header('Location: http://example.com');
And to check for session cookie name use this:
session_start();
echo 'Session cookie name is: ' . session_name();
By default its 'PHPSESSID', but you or server admin could change that so check it out!
Hope this helps!