I would like to maintain 3 $_Session variables after login. My login modal submits to my index.php page and this seems to be the only place I can access the session variables I set when the user logs in. How do I pass these variables to the next page the user visits? I know I can use hidden inputs in forms but what if the brows the site using the menu? I would like to store a users session variables in a session include file but I have the same issue passing the values of the variables from page to page.
-Mike
File a.php:
<?php
session_start();
$_SESSION['saveme'] = 'from file A';
?>
File b.php:
<?php
session_start();
echo $_SESSION['saveme']; // if you visited a.php previously, you will see "from file A"
?>
Setting a session variable in any file makes it available anywhere else.
You can store you values in session on one page(index in your case as you mentioned) then later on you can get those values on any page if session in started on that page. Session store those value till same session alive.
code to set values in session:
<?php
// Start the session
session_start();
?>
<?php
// Set session variables
$_SESSION["xyz"] = "xyz";
$_SESSION["abc"] = "abc";
echo "Session variables are set.";
?>
Code to get session values:
<?php
// Echo session variables that were set on previous page
echo "value of xyz is " . $_SESSION["xyz"] . ".<br>";
echo "value of abc is " . $_SESSION["abc"] . ".";
?>
The form of your modal
<form action="index.php" method="post">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
</form>
Then you catch it in your index.php
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
// Check if user exists and password matches
$_SESSION['username'] = $_POST['username'];
$_SESSION['logintime'] = time();
$_SESSION['something'] = 'else';
}
In any other page you can use the values like
<?php
session_start();
if (isset($_SESSION['username'])) {
echo 'Welcome ' . $_SESSION['username'];
}
All who have provided answers thank you. This overlooked detail was all on me and though I have been out of the dev game for a while I should have known better.
My hosting service by default makes all file permissions read/write only...to access session variables I changed to read/write/execute and was successful.
Again thanks!
Related
I have test.php:
<html>
<?php
if (!isset($_SESSION))
{
echo 'session is not yet set';
session_start();
$_SESSION['comments'] = array();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="comment">
Click the button!
<input type="submit"/>
</form>
<?php
array_push($_SESSION['comments'], $_GET['comment']);
echo 'Current array count: ' . count($_SESSION['comments']) . '<br>';
foreach($_SESSION['comments'] as $comm)
{
echo $comm.'<br>';
}
?>
</html>
What should happen is that any text entered in the textbox should be pushed to the session array, but every time I click on submit, what is printed is the text I just entered instead of appending/storing the previous entries. I only get 1 as the array count all the time.
Every time I hit submit, session is not yet set always shows at the top of the page even when I have the if condition.
I can't seem to find what's wrong?
You need to do this:
<?php
session_start();
if (!isset($_SESSION))
{
?>
Otherwise you have header output from the HTML tag and the session can't start properly.
You should start the session at the top of the page always.
session_start(); //start the session
Then we can check session is exist or not.
if(!isset($_SESSION['user'])){
// your code
}else{
// your code
}
session_start() does not just start a NEW session. If the client already has a session it resumes that session. PHP Manual
If you are using sessions, just have session_start(); at the top of the page and PHP will do the lifting of starting or resuming a session.
Hey guys I'm trying to pass a php variable to another page. I tried it with sessions but no result.
newspaper.php
$newspaper= $newspaper['newspath'];
print_r($newspaper);
this outputs:
path/to/the/newspaper.
Now I want to use the variable in the second page.
newspaperviewer.php
echo $newspaper;
$SESSION = $newspaper;
I tried the first one but no result. The second one seems to be faulty.
Hope you guys can help me out.
Session is what you are looking for. A session variable can store a value and use this value on all pages of your project.
First thing to do is to start session on each file on your project. You can do this like this example
<?php
session_start(); //declare you are starting a session
$_SESSION['newspaper'] = "New York Times"; //Assign a value to the newspaper session
?>
On the other file you can use the value of the session by trying something like this
<?php
session_start(); //always start session don't forget!!
echo $_SESSION['newspaper'];
// This will echo New York Times
?>
Store the variable after starting session on page A, like so:
// FIRST PAGE (foo.php)
session_start();
$_SESSION['name'] = 'Jack';
Now, on the second page (or any page that you want to have access to $_SESSION, simply do the same but pull the variable.
// SECOND PAGE (bar.php)
session_start();
$name = $_SESSION['name'];
$_SESSION['name'] = null; // Or use session_unset() to delete all SESSION vars.
And that's how you pass variables using $_SESSION.
Please use this code to set session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
You can write like this
newspaper.php
session_start();
$newspaper= $newspaper['newspath'];
$_SESSION['newspaper'] = $newspaper;
Now you can use this session variable in
newspaperviewer.php
session_start();
$newspaper = $_SESSION['newspaper'];
echo $newspaper;
session_unset(); // remove all session variables
First
newspaper.php
$newspaper= $newspaper['newspath'];
//print_r($newspaper);
session_start(); //it starts your session here
$_SESSION['newspaper']=$newspaper; //it sets a session variable named as newspaper
Second
$newspaper= isset($_SESSION['newspaper'])?$_SESSION['newspaper']:''; //checks and sets value
echo $newspaper; //outputs value
For more see session_start
http://php.net/manual/en/session.examples.basic.php
First you will need to start the session by using session_start() at the top of your page. Second, a session variable is written like this: $_SESSION['foo'].
I suggest you read these pages to get a better understanding of what's going on.
http://php.net/manual/en/reserved.variables.session.php
http://www.w3schools.com/php/php_sessions.asp
I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.
My php website flows like this:
Page1.php has an html form which POSTs to Page2.php
Page2.php stores all the POST data into SESSION variables and has a button leading to Page3.php
Page3.php has another form which POSTs its data to Page4.php
Page4.php then stores all its POST data into SESSION variables
My problem is that it may be nessicary for a user to click the back button on Page4.php to go back to Page3.php and change some input. AS im sure your all aware when they get back to Page3.php the form will be blank as the entire page is re-rendered in its default state.
To get around this and re-display the user's previous input im doing this:
<input value="<?php echo $_POST["guest1Ticket"];?> " type="text" name="guest1Ticket" id="guest1Ticket" onblur="isTicketNumber(this)" size ="22"/>
This being the important part - <?php echo $_POST["guest1Ticket"];?>
This works but creates another problem for me. If the user goes back to Page1.php (before colsing their browser) and starts the process over again when they get to Page3.php the data from their last run through will be loaded into the form.
What I figure I need to do is clear all of the sdession variables when the user visists Page1.php. I tried to to that like this:
<?php
session_start();
session_unset();
session_destroy();
?>
(The above is at the very top of my file with no whitespace before the first character.)
No Warnings are generated when Page1.php loads but the session variables are not getting unset. When I get to Page3.php the data from the last run is still being entered into the form.
How can I clear my session data correctly?
BTW I only need this to work in Chrome and thats where im testing.
Only use session_unset() for older deprecated code that does not use $_SESSION.
see session_destroy manual
example you can try and see how it works
session.php
<?php
session_start();
$_SESSION = array('session1'=>1,'session2'=>2);
echo $_SESSION['session1']; //1
$_SESSION['session1'] = 3;
echo "<pre>";
print_r($_SESSION); //session one now updated to 3
echo "</pre>";
$_SESSION = array();
if ($_SESSION['session1']) {
echo $_SESSION['session1']; // IS NOW EMPTY
} else {
echo "woops... nothing found";
}
?>
<p>
<a href="destroyed.php">NOW GOING TO DESTROYED PHP<a/>
</p>
<?php
session_destroy();
?>
destroyed.php
<?php
session_start(); // calling session start first on destroyed.php
print_r($_SESSION); // prints Array ( )
?>
From the documentation:
If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used,
use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);
And take care about session_destroy:
session_destroy destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session
Use session_unset(). Like this:
<?php session_start(); ?><!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["variabletounset"] = "I am going to be unset soon along with all of the other session variables.";
print '<pre>' . "\n";
print_r($_SESSION);
print ' </pre>' . "\n";
session_unset();
print ' <pre>' . "\n";
print_r($_SESSION);
print ' </pre>' . "\n";
?>
</body>
</html>
This would output:
Array
(
variabletounset => I am going to be unset soon along with all of the other session variables.
)
Array
(
)
I have faced a problem in all of my php projects is that since i used OOP is that if there is a user submitting a form
when it goes to processing it and if it has an error i save a message in the session and redirect them to the same page
this is a sample and of course when it redirects it wipes all the fields that was there
like let's say i have a register form that had
<?php if(!empty($message)) { echo $message } ?>
<form action ="forms/register.php">
first name: <input type="text" name="first_name" />
username:<input type="text" name="username" />
<input type="submit" value = "submit" />
</form>
and this is what the code in forms/register.php
if(isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$username = $_POST['username'];
if(empty($first_name) || empty($username) {
$session -> message("please fill in all the fields");
redirect("../register.php");
} else {
// do something else like insert query
}
}
my problem is if first_name or user_name is empty and it redirects to register.php
and it echos the error message no problem in that
but the fields are empty the first_name and the user_name are empty
so the user has to fill it all again
so one of my friends suggested to save it in the session or something
so i would like to know if that is possible then how and what i mean by how so nobody would get it wrong, i mean the way not the code to just copy it and paste it
Thanks in advance
and sorry for being long and annoying
You can store whatever values you want to keep persisted in the form after the page redirects in session variables, then retrieve those values on the form page and echo them in the value attribute of the form elements.
session_start(); $_SESSION['nick'] = $_GET['nick'];
more / better examples:
http://php.net/manual/en/function.session-start.php
Not sure what issue you exactly are facing (also what $session is inside your workflow?).
However, i recommend using PHP inbuild session support.
http://php.net/manual/en/features.sessions.php
From the above link itself:
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views']=$_SESSION['views']+1;
}
else
{
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
}
?>
Above code simply keeps track of page views. $_SESSION variable persists between page loads and you should be using the same for all your session requirements.