PHP Session Help [closed]
I have read up on how to use Sessions in PHP but I am struggling to understand and implement it. After looking at some examples on Google, they all seem vague and too complex. What I am trying to implement is the following:
The user logs in, when the submit button is pressed, they are redirected to another page where the user's name will show 开发者_如何学JAVAup. Could you help me with doing this by showing simple examples?
Start the session on each page
<?php session_start(); ?>
Set a variable in the session array.
<?php $_SESSION['username'] = 'Roel Veldhuizen'; ?>
And echo a variable, on the same or other page
<?php echo $_SESSION['username'];?>
Can't make it any simpler. You should do some checkings for security.
php.net provides a lot of documentation and examples. I've written a bit of example code below.
Script that handles the form input:
session_start();
$_session['name'] = $_POST['name'];
header('location: nextpage.php');
nextpage.php
session_start();
echo 'Your name is: '.$_SESSION['name'];
No clue what you are having trouble with, but seems like you have a form that submits to a PHP page, and want the username to display on that page, and be displayed on all pages afterwards.
Sample Form:
<form name="submitName" action="saveName.php" method="POST">
Name: <input type="text" name="usersName" /><br>
<input type="submit" value="Continue" />
</form>
PHP to Process Form (saveName.php
)
<?php
session_start(); // Starts the session so you can save the name
$name = $_POST['usersName']; // Get the name submitted
$_SESSION['name'] = $name; // Save the name in a session
echo strip_tags($name); // Output the user's name to the HTML page, after removing PHP and HTML tags from string
?>
On later pages, $_SESSION['name']
contains the user's name.
<?php
session_start();
if(isset($_SESSION['name'])) {
echo $_SESSION['name'];
}
else {
echo <<<USERFORM
<form name="submitName" action="saveName.php" method="POST">
Please enter your name: <input type="text" name="usersName" /><br>
<input type="submit" value="Continue" />
</form>
USERFORM;
}
?>
If you redefine your question, we can help more.
If you want to implement a Login system using Session. in my earlier post i have explained on how to deal with it.
have a look at this post and check for my answer. Login System Using PHP Session.
精彩评论