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! :-)
Related
I'm able to pass a variable from a link on my first page to the 2nd page, but i'm having a hard time passing that variable into the third page. How can i pass the variable to the third page?
First Page is a HTML Page
Go to Page Two
Second Page is a PHP Page
<?php
echo $_GET["Page"];
?>
Third Page is a PHP Page
???
To pass a variable along from one page to another you can choose from multiple options:
Sessions
Cookies
Storage (File or Database)
Sessions
The first page:
<?php
// Prepare to use sessions (This should be at the top of your page)
session_start();
if (!isset($_SESSION['test']) && isset($_GET['test'])) {
$_SESSION['test'] = $_GET['test'];
header("Location: secondpage.php");
exit;
}
The second page:
<?php
session_start();
// Output session
var_dump($_SESSION['test']);
Cookies
First page:
<?php
if (isset($_GET['test'])) {
setcookie('test', $_GET['test'], time() + (86400 * 30), "/");
}
Second page:
";
echo "Value is: " . $_COOKIE['test'];
}
Files and Databases
This is too big a subject to discuss in one answer. However, there are tons of tutiroals that can learn you all you need to know about PHP and MySQL.
Example
First page:
Go
Second page:
<?php
session_start();
if (isset($_GET['page'])) {
$_SESSION['page'] = $_GET['page'];
}
header("Location: page_three.php");
exit;
?>
Third page:
<?php
session_start();
// Will echo two
echo $_SESSION['page'];
?>
Resources
PHP - Sessions
PHP - Cookies
You have two main options:
you can keep linking the pages with url parameters
Go to Page Two
Go to Page Three
This solutions is quite inconvenient if you want to keep the "page" value for a long term
The best solution as user1234 said is to store the value in the session.
if your first page MUST be html and you can't store it at begining you can do in any of your php pages
$_SESSION['Page'] = $_GET["Page"];
So I've scoured w3schools and this fine website for some time but I can't figure this out.
I have a script that creates a cookie in the users session upon loading the browser, and another script that will check the value of said cookie and respond with 2 echo's depending on the value.
Script to create the cookie is:
<?php
$cookie_name = "CTF";
$cookie_value = "ChangeThis";
if(!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, time() + 86400, "/", NULL);
}
?>
My IF check for the values is as follows:
<?php
if($_COOKIE[$cookie_value] = "CTF") {
echo "Congratulations. Your token code is 4HeWPzK63Lf5NkGS";
} else {
echo "Your cookie is not set yet.";
}
?>
The code works, and when the cookie is changed to CTF it echo's the correct line. However, when I then delete the cookie and refresh the page, essentially resetting the cookie back to the value of "ChangeThis", the first echo still appears on the page.
Can someone point me in the right direction?
The issue is your if condition. You have used = instead of ==. You are assigning the value instead of comparing. The condition checks if the assignment is successful or not. What you need is the below statement:
if($_COOKIE[$cookie_name] == "CTF")
Also, the cookie value is not "CTF", that's the cookie name, you should compare with the value you are setting it to.
So I have a problem where I have several $_SESSION values defined and need to be sent to the next page. Here is a quick look at the meat of my problem.
login.php
session_set_cookie_params(900, '/', 'localhost:8080/test/');
session_start();
$_SESSION['first_name'] = "Moe";
$_SESSION['last_name'] = "Joe";
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/test/admin_console.php?" . SID);
exit();
?>
On the next page, I expect my $_SESSION['first_name'] and $_SESSION['last_name'] to be defined as they have been set by the code above. The following is the meat of my code in the next page
admin_console.php
session_name('AdminLogin');
session_start();
#Set page title and include HTML header
$page_title = 'Administrative Console';
include('./header.inc');
$mysession = session_get_cookie_params();
$msg = $_SESSION['first_name'];
echo "Is the thing set? " . $msg . "<br />";
?>
The problem is, i get the following error:
*Notice: Undefined index: first_name in C:\wamp\www\test\admin_console.php on line xx*
I can't for the life of me figure out why $_SESSION['first_name'] wont retain its value from previous page. i have session_start() in every page and i even went as far as to add several lines to completely kill the session at the end of this page
<?php
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-300, '/', '', 0);
?>
So my echo statement should display the value that is entered in $_SESSION, but to no avail. Any help?
OH MY GOD, it is the worst mistake in the world.
Google Chrome, for some reason, saves previous attempts or pages. So during my initial tests, the page failed. But when I fixed the code, the browser still retained the old style.
I just now had this feeling in my gut to try the code in the Incognito mode, and it WORKED!
Lesson Learned: If your code looks perfect and you're still getting same error no matter what, try a different browser or clear out browser cache.
It's just a notice (warning). You can set error_reporting(7); to get rid of this message.
Your code looks fine , check your php info "session section".
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)
I have a log in form that allows persistent login and regular session. Long story made short, when users are in their account, they can change password, email and stuff. But for that, I need to get their username from their session or cookie first (so I can do the proper SQL query).
I try to do so with this code:
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else
if(isset($_COOKIE['username']))
{
$username = $_COOKIE['username'];
}
But if I try to echo $username, I keep getting "undefined variable". Why is that?
I noticed that if I put a session_start(); at the top. I get the proper username for session but not for cookie of course. How can I solve that?
The weird part (for me) is that I got the exact same code (well that part) in another page and username isn't undefined.
PS: If something isn't clear or more information is needed, please tell me.
EDIT
I tried this:
function accountValidation()
{
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']))
{
$cookie = $_COOKIE['username'];
$explode = explode(' - ', $cookie);
$username = $explode['0'];
}
echo $username;
}
accountValidation();
And it worked ... So if I put it into a function and then call it, it works?! What is the diference? Why does it need to be into a function for it to work???
If you set certain cookie, it would be available to you from next reload. As $_COOKIE is set when a page head is called. You wont be able to retrieve the cookie from the same page which has set the cookie. I hope you got what i meant. If not let me know I would give an better example.
EDIT:
Example
<?php
session_start();
$_SESSION['test'] = 'test1success';
echo $_SESSION['test'];// would display test1success
if (!isset($_COOKIE['test2']))
{
setcookie("test2", "test2success", time()+3600);
}
echo $_COOKIE['test2'];
// wont display test2success when you load the page for first time
// reload it & it would display test2success
?>
Explanation:
The first thing you need to understand is that the cookie is stored on your PC(browser) when the page is loaded. The client (i.e. browser) sends cookie headers to the server & does the page execution. The values set by set_cookie during page execution are set on the client pc, and the server doesn't know about the new values just set - unless you reload the page & the cookie header is sent back.