Reputation: 1
it seems to be simple but anyhow i can't pass my sessionvariable from the first page to the second page. I have searched for solutions but can't find any. As far as i know i am starting the session on bothe pages before sending any headers.
code on page1
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="page2.php" method="POST">
<input type="text" name="username" id="username">
<input type="submit" name="submit" id="submit">
<?php if(isset($_POST['submit'])) {
$username = $_POST['username'];
$_SESSION['username'] = $username;
}
?>
</form>
</body>
</html>
Code on page 2
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "This is from my session: "." ". $_SESSION['username'];
?>
</body>
</html>
So on the second page (page2.php) i get this error:
Notice: Undefined variable: username in C:\xampp\htdocs\page2.php on line 12
This is from my session:
Upvotes: 0
Views: 588
Reputation: 755
There upvoted answer works fine. The below should also work. I think the basic thing is to check if a session can be passed from one page to another. Please see the below code. Two things basically - 1. Form action should be set to same page & 2. Redirect after session is set
Note: No change is needed for page2.php
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="username" id="username">
<input type="submit" name="submit" id="submit">
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$_SESSION['username'] = $username;
header("Location: page2.php");
}
?>
</form>
</body>
</html>
Upvotes: -1
Reputation: 970
Looking at your code - the mistake is on page2.php, you submit the form to page2.php but you didn't set any value in page2.php.
It should be like this:
page1
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="page2.php" method="POST">
<input type="text" name="username" id="username">
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>
page 2
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
if(!empty($_POST['username'])) {
$username = $_POST['username'];
$_SESSION['username'] = $username;
}
echo "This is from my session: "." ". $_SESSION['username'];
?>
</body>
</html>
Upvotes: 0
Reputation: 147
Your form posts to page2.php
, so the session-setting bit isn't being reached on page1.php
You need to add that code to page2.php
instead:
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$_SESSION['username'] = $username;
}
Upvotes: 9