Checking the session value that is available or not - php

I wrote the following login.php file.
<?php
session_start();
//Check everything and if everything is correct and the username and password is correct and available
echo "Successfully";
$_SESSION['login_user'] = $username;
// and etc
?>
Now if the username is session as the the result $_SESSION['login_user'] value is session also.
and then I create check-session.html file and it is as follows:
<html>
<body>
<form method = "POST" action = "check.php">
<input type = "submit" value = "check-session">
</form>
</body>
</html>
And then the check.php file is as follows:
<?php
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>
But the problem is when the login operation is successfully and now I want to know that the session is created really or not, after clicking the check-session button in the check-session.html page, I see the result from server as the follows:
session is not available
Also for more information I use wamp server.

Put session_start(); in the start of every page that's using sessions or is related to them in any way.
In the start of your check.php file
<?php
session_start();
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>

You can solve this problem by making a separate file for setting session and include that file on the starting of each logged in page.
this is c.php for checking session...
<?php
include 'b.php';
if(isset($_POST['check_session']))
{
if(isset($_SESSION['login_user']))
echo "session is available";
else
echo "session is not available";
}
?>
<form method = "POST" action = "c.php">
<input type = "submit" name="check_session" value = "check-session">
</form>
a.php for login
<?php
if(isset($_POST['login']))
{
header("Location: c.php");
}
?>
<html>
<body>
<form method = "POST" action = "a.php">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
and also make b.php simply for setting session using session_start()

Related

Cannot access html form data in a post message (PHP)

I am trying out a php sample code given here: https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
This gives a log in form, where you can register username password and then log in with a registered user. A welcome page is only visible after you have logged in, and the welcome page shows the specific username of the currently logged in account.
I am trying to modify the welcome.php given in the above link, to add a data entry form that will save some personal data like name and age to a mariadb database. Here is my version of the welcome.php file:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]);
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
</p>
<p>Enter your data here:</p>
<!-- <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> -->
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="save" value="submit">
<!-- <input type="submit" class="btn btn-primary" value="submit"> -->
</form>
</body>
</html>
If I understand this correctly clicking the submit button should generate a post message which should be captured by the php script at the beginning of the file. This much is happening, but I cannot display the content of the text box given by <input type="text" name="name">. The var_dump($tempvar); in the php code at the beginning comes up with String(0) "". I have tried moving the php code to a separate file (as given here in insert.php) instead of attempting to process the post message in the same file, but I am getting the same result. I am not getting any errors.
How do I access the contents of the text box in the post message handler? I am testing this in XAMPP on Windows 10.
Did the example with the login work correctly? This would prove that POSTing data works.
Which version of PHP are you using? There was a feature called register_globals up to 5.4.0 which allowed accessing POST data via named variables. Since you are setting $name = "" this could overwrite your data. I would take it out at that position anyway (use an else clause if necessary). If you have register_globals active either update PHP or turn it off to avoid confusion.
The next step to debug the issue is to print the whole array of $_POST like mentioned here but more pretty
if($_SERVER["REQUEST_METHOD"] == "POST"){
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
This will show you what values were actually POSTed.
Same can be done with the $_SERVER array like this
echo '<pre>';
print_r($_SERVER);
echo '</pre>';
die();
$uname=htmlspecialchars($_SESSION["username"]);
The die() command will halt execution so you need to remove it when you want the script to continue.
Your code works fine for me. I ran it in my system, it shows the submitted name with the var_dump i.e. string(18) "Md Shabbir Hossain".
There are some flaws that I would fix.
Initial user get to Welcome.php.
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]); //username is not defined or it does not exists yet.
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
I would do this:
<?php
// Initialize the session
session_start();
//Check if the user already logged.
if(!isset($_SESSION["loggedin"])){
//Redirect
header("location: login.php");
exit;
}
// Check if post to login is submitted
if(isset($_POST['save'])){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
$uname = '';
//Check if Username is submitted
if(isset($_POST['username'])){
$_SESSION["username"] = $_POST['username'];
$uname=htmlspecialchars($_SESSION["username"]);
}
$name = "";
$age = 0;
//For test
var_dump($_POST[]);
}

Cookies vs Sessions | I get different result

What I want to achieve,
The user enters the one_page.php and we require('form.php') for user to fill while $_SESSION['foo'] isn't set.
The user submits the form and a $_SESSION['foo'] is set.
We header ('Location: one_page.php') (practically like reloading)
We get in the if we unset($_SESSION['foo']) and we require('something_else.php').
If the user reload the site.php or re-enter it he's going to get the form.php again.
I will not show you the actual code because it's too big and I don't want to paste only parts of it but I reproduced the problem at two examples bellow.
Using cookies the code were running exactly as intended.
Using session it's like we get in this if we unset($_SESSION['foo']) but then we leave the if and get into else.
When I set the session for example at page1.php and redirect the user to page2.php to unset the session everything seems fine. I just can't get it work when I create the session at the same page where I unset it.
Examples
Using Cookies We get in the IF when we press the button
<?php
if (isset($_POST['submit'])) {
setcookie('foo', 'foo', time() +3600);
header('Location: one_page.php');
}
if (isset($_COOKIE['foo'])) {
setcookie('foo', 'foo', time() -3600);
echo "We entered the IF"; //require('something_else.php')
} else {
echo "We entered the ELSE"; //require('form.php')
}
?>
<!-- The form which is required in my case -->
<html>
<body>
<form method="post">
<button name="submit">Button</button>
</form>
</body>
</html
Using Sessions We are in the ELSE no matter what
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['foo'] = "foo";
header('Location: one_page.php');
}
if (isset($_SESSION['foo'])) {
unset($_SESSION['foo']);
echo "We entered the IF"; //require('something_else.php')
} else {
echo "We entered the ELSE"; //require('form.php')
}
?>
<!-- The form which is required in my case -->
<html>
<body>
<form method="post">
<button name="submit">Button</button>
</form>
</body>
</html>
I could just use cookies but this is bugging me so much for hours now.
Any thoughts?
Adding exit() just after the header('Location: one_page.php') fixed the problem.
The unset($_SESSION['foo']) were running before the redirection as Dagon said.
Fixed
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['foo'] = "foo";
header('Location: one_page.php');
exit();
}
if (isset($_SESSION['foo'])) {
unset($_SESSION['foo']);
echo "We entered the IF"; //require('something_else.php')
} else {
echo "We entered the ELSE"; //require('form.php')
}
?>
<!-- The form which is required in my case -->
<html>
<body>
<form method="post">
<button name="submit">Button</button>
</form>
</body>
</html>
Thank you Dagon!

Echoing a name from session php

I'm a student and I'm making a quiz using php and mysql, my problem is I'm trying to echo a name on the results page but it doesn't work.
My first page is an index page where I create a form which gets the users name which I send to my quiz.php page.
<form method="post" action="quiz.php">
<img src="pictures/indeximage.jpg" alt="horrormovies" width="1024" height="640">
<p>
Please Enter Your Name
<br>
<input type="text" name="name">
</p>
<input type="submit" name="submit" value="Start">
</form>
on my quiz.php page i put make a variable and put it in a session
<?php
//start session
session_start();
$var_name=$_REQUEST['name'];
$_SESSION['ses_name']=$var_name;
?>
On my results page I have this
<?php
session_start();
$var_name=$_SESSION['ses_name'];
?>
<p>
Thank you for taking the quiz <?php echo $var_name; ?>.
</p>
Use isset for assign value in session variable. for good practice.
if(isset($_POST['submit']))
{
//start session
session_start();
$var_name=$_REQUEST['name'];
$_SESSION['ses_name']=$var_name;
}
quiz.php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['ses_name']=$_REQUEST['name'];
}
Try this code :-
results page
<?php
//start session
session_start();
if(!empty($_SESSION['ses_name']))
{
?>
<p>Thank you for taking the quiz <?php echo $_SESSION['ses_name']; ?>.</p>
<?php
}
else{
echo 'session not set ';die;
}
?>

PHP Session won't keep array variables

I have an Index page with login form, a verification page called Login and content.
Index is fairly simple: if logged in, redirect to Content, otherwise display login form and POST to Login page
index.php:
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');
} else {
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="POST" action="login.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="usr"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
<?php } ?>
Then we have Login verification: compare the POST vars with coded variables, if all is good, set Session variables and redirect to content.
login.php:
<?php
session_start();
if($_POST['usr']=='user' && $_POST['pswd']=='password'){
$_SESSION['usr'] = 'user';
$_SESSION['pswd'] = 'password';
header('Location: content.php');
} else {
echo "post: ";
print_r ($_POST);
//header('Location: index.php');
}
?>
Then we have the Content page, check that the Session is set and display content, otherwise PRINT_R
content.php:
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
The process works, up to the Content page. I keep getting a blank SESSION array, and when I try going to Index, it pretends I never logged in. what am I missing?!
Edit: in The code above, content.php is trying to check if the session is set. If it is NOT set it will show me a blank array (for debugging purposes, but normally I want it to go back to index, since the user is not properly connected),
if it IS set, it will echo "you are logged in". It is also including a page called 'logoff.html' as that page has a button to destroy the session.
Even without the IF statement, simply running a print_r ($_SESSION); returns a blank array. This means there is no problem in the IF statement, but something that happens before it.
Solution: I didn't know about this before, but some hosting sites require some PHP set up, before they can store PHP sessions. I went to the knowledge base of my hosting service and searched for "session", and found an explanation on how to set up the php.ini file to save my sessions in the correct path.
Make sure sessions are configured properly. For example, is the session save handler set correctly? If using files, does it have permission to access the specified folder? If memcache, is that set up properly?
This would be the main reason for session variables to not be saved.
change this
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
i think in your code when session not set then it will print so change it with
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd']))
{
// session is set
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
}
else
{
/// session is not set
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>

posting variable from php file to another php file

I show similar threads, but could not get clear through them.
page1.php
<?php
$id = 1234;
//Post $id to page2.php
?>
page2.php
<?php
$user_id=$_POST['id']; //should receive id posted from page1.php
?>
Actually you are not sending the id parameter to your Page2.php
Page1.php
<?php
$id = 1234;
header("location:page2.php?id=$id");//Post $id to page2.php
?>
Page2.php
<?php
echo $user_id=$_GET['id']; //should receive id posted from page1.php
?>
You can use sessions for this also, to show you what your options are.
This works with a POST method (use all in one file for the form method)
Form method (page1.php)
<?php
session_start();
$id = $_SESSION["id"] = $_POST['id'];
if(isset($_POST["submit"])){
echo $id;
echo "<br>";
echo "<a href='page2.php'>Click to see session ID on next page</a>";
}
?>
<form action="" method="post">
Enter ID:
<input type="text" name="id">
<br>
<input type="submit" name="submit" value="Submit">
</form>
page2.php
<?php
session_start();
$user_id=$_SESSION["id"];
echo $user_id; // will echo 1234 if you entered "1234" in the previous page.
Regular session method (page1.php)
<?php
session_start();
$id = $_SESSION["id"] = "1234";
echo $id; // will echo 1234
page2.php
<?php
session_start();
$user_id=$_SESSION["id"];
echo $user_id; // will echo 1234
Footnotes:
You could then use the same (session) variable for a member's login area, database for example.
It is important to keep session_start(); included inside all pages using sessions, and at the top.
Should you be using a header() in conjunction with this, then you will need to add ob_start(); before session_start();
Otherwise (as Eitan stated in a comment) "$_SESSION value will be unresolvable."
header() example:
<?php
ob_start();
session_start();
$user_id=$_SESSION["id"];
if(isset($_SESSION["id"])){
header("Location: members_page.php");
exit;
}
else{
header("Location: login_page.php");
exit;
}
You could also replace: if(isset($_SESSION["id"])) with if(!empty($_SESSION["id"]))
To implement a logout page, you would need to use session_destroy();

Categories