Cookies vs Sessions | I get different result - php

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!

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[]);
}

Checking the session value that is available or not

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()

How to prevent user from bypassing php authentication

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

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 } ?>

Not able to redirect to next page

I am using Win XP os and XAMPP. I was using eclipse as the editor. In Eclipes I was not able to redirect next page so now I have installed Zend Development Environment.
Now also I am getting the same problem.
My Code is
HomePage.php
<html>
<body>
<form name="Form1" id="FormId" action="Welcome.php" method="post">
name : <input type="text" name="txtName">
Phone Number : <input type="text" name="txtPnum">
<input type="submit" name="SubmitIt" value="Submit It">
</form>
</body>
</html>
And Welcome.php is
<?php
ob_start();
session_start();
if(!($_SESSION['UName']))
{
$_SESSION['UName']=$_POST['txtName'];
}
if(!($_SESSION['Ph Num']))
{
$_SESSION['Ph Num']=$_POST['txtPnum'];
}
?>
<html>
<body>
Welcome <?php
if(isset($_SESSION['UName']))
{
echo $_SESSION['UName'];
}
else
{
echo "Session not set<br/>";
echo "{$_SESSION['UName']}";
echo "The session contains <br>";
print_r($_SESSION);
}
?>
</body>
</html>
Its working fine (redirecting to next page) in the Browser but its not working in the debug mode. Both in Eclipse and Zend Development Environment.
Instead of show the content of the next page, it showing the page name.(Welcome.php in my example).
Should I need to install any other extra softwares or code itself worng.... Whats the problem. Please suggest me.
Thanks in advance....!
which part is supposed to make a redirection, i don't see any header('Location: redirect.php') or something
and why do you use ob_start() here .
you didnt release the output buffer add ob_get_clean(); in the end
<?php
ob_start();
session_start();
if(!($_SESSION['UName']))
{
$_SESSION['UName']=$_POST['txtName'];
}
if(!($_SESSION['Ph Num']))
{
$_SESSION['Ph Num']=$_POST['txtPnum'];
}
ob_end_flush();
?>
<html>
<body>
Welcome <?php
if(isset($_SESSION['UName']))
{
echo $_SESSION['UName'];
}
else
{
echo "Session not set<br/>";
echo "{$_SESSION['UName']}";
echo "The session contains <br>";
print_r($_SESSION);
}
?>
</body>
</html>
try to add this at the end of your code i am pretty sure it is because you are not releasing the output buffer, although i think it should have done it automatically
echo ob_get_clean();
Update:
I am not really sure why you are using the $_SESSION variable here, but is you want to fix the problem, you can use for example $uname instead of $_SESSION['UName'];
Welcome.php
<?php // at the beginning of your file, no spaces or newline
session_start();
$uName=$_POST['txtPnum'];
$txtPnum=$_POST['txtPnum'];
$_SESSION['UName'] = $uName;
$_SESSION['PhNum'] = $uName;
?>
<html>
<body>
Welcome <?php echo $_SESSION['UName']; ?>
</body>
</html>
you get rid of the ob start since you are still debugging your code. and try one step at a time.
Wish you good look.

Categories