PHP: session variable lost on clicking form submit button? - php

When I click form submit button session variable lost and it shows message that session is not set. I have another confusion that it has only problem when I set session of login variable or those variables which are set in other page of my site.When I set some random session variable on the top of this page it works fine and session variable does not lose anymore. I have also checked some other related links in stack overflow but nothing found solution
Here is the code of addProduct.php page
<?php
//var_dump($_SESSION);
if(!(isset($_SESSION['login']))) {
echo "session is not set";
}
else {
//header("location:index.php");
echo "session is set";
//$user_email=$_SESSION['user_email'];
?>
<html>
<body>
<form action="addproduct.php" method="post">
<input type="text" name="name" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
// $_SESSION['user_email']=$_SESSION['user_email'];
echo $name;
}
?>
<?php }
?>
Code of index.php (header file) page from where I get into this page
<?php
session_start();
include("db.php");
?>
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<title>Home</title>
</head>
<body>
Home</br></br>
<?php if(isset($_SESSION['login']) ) {
if($_SESSION['user_status']=="admin")
{
?>
Post an Ad</br></br>
<?php }
}
?>
<?php if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email']))
{
?>
<?php echo $_SESSION['user_fname'] . " " . $_SESSION['user_lname'] . " " . $_SESSION['user_status']; ?></br></br>
<?php
}
else
{
?>
Login</br></br>
SignIn</br></br>
<?php }
if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email']))
{
?>
Logout</br></br>
<?php }
?>
<div id="content">
<?php
if(isset($_GET['page']))
{
$p=$_GET['page'];
$page = $p . ".php";
//echo $page;
if(file_exists($page))
{include($page);
}
elseif($page=="")
echo "this is home page";
else
{echo "Not found";}
}
else
{
include ("showAds.php");
}
?>
</div>
</body>
</html>
Code of login.php
<?php
session_start();
if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email'])) {
header("location:index.php");
exit();
}
else
{
?>
<html>
<head><title>Login</title></head>
<body>
<form action="login.php" method="post">
<input type="email" name="user_email" placeholder="USER EMAIL" REQUIRED>
<input type="password" name="user_password" placeholder="USER PASSWORD" REQUIRED>
<input type="submit" name="Go" value="SUBMIT!" placeholder="USER NAME" REQUIRED>
</br></br>SignIn with new account</br>
</form>
<?php
include("db.php");
/*if(isset($_POST['Go'])) { SIGNUP
$user_name = $_POST['user_name'];
$user_password = $_POST['user_password'];
$user_email = $_POST['user_email'];
echo $user_name . "<br>";
echo $user_email . "<br>";
echo $user_password . "<br>";
$sql = "INSERT INTO user(user_name,user_email,user_password) VALUE ('$user_name','$user_email','$user_password')";
if(mysqli_query($conn,$sql))
{
echo "stored";
header("location:http://localhost/window.php");
}
else
{
die(mysqli_error($sql));
}
}*/
if(isset($_POST['Go']))
{
$user_email = $_POST['user_email'];//real_escape_string
$user_password = $_POST['user_password'];
$login_query="SELECT * FROM user WHERE user_email='$user_email' AND user_password='$user_password'";
$run=mysqli_query($conn,$login_query);
if(mysqli_num_rows($run)>0)
{
$res = mysqli_query($conn, "SELECT * FROM ecommerce.user WHERE user_email='$user_email'");
while ($record = mysqli_fetch_array($res)) {
$_SESSION['user_fname']=$record['user_fname'];
$_SESSION['user_lname'] = $record['user_lname'];
$_SESSION['user_status'] = $record['user_status'];
$_SESSION['user_id'] = $record['user_id'];
$_SESSION['user_password'] = $record['user_password'];
}
$_SESSION['user_email']=$user_email;
$_SESSION['login']="true";
//echo $_SESSION['user_fname'] . $_SESSION['user_lname'];
header("location:index.php");
exit();
}
else
echo "<p style='color: red; margin-top: -28px;'>User name or password incorrect</p>";
}
?>
</body>
</html>
<?php }?>

This error you showed in your other question which was marked as an exact duplicate of this one:
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\ecommerce\showAds.php on line 2
Your showAds.php page which you didn't include, (most likely) contains session_start(); and it should be removed from inside that file.
index.php has an include and session_start();
else
{
include ("showAds.php");
}
So one of your if statements failed.
That is why you're getting that error.
All pages using sessions require that session_start(); be included and should be the first line of your script, which isn't shown in addProduct.php.
Also make sure you're not outputting before header. If you are, consult the following on how to fix it:
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.

You have to add session_start(); in your addProduct.php to be able to access session contents!

Related

PHP Session not recognizing variable when heading to another page

So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/> 
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here

How to open a page only, if someone write the right password/username

I am working on a simple login form with sessions..Here is my index.php code
<?php
ob_start();
session_start();
?>
<?
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
?>
<html lang = "en">
<head> </head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password']))
{
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else $msg = 'not working';
}
?>
</div> <!-- /container -->
</div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" >
<?php echo $msg; ?>
<input type="text" name="username">
<input type="password" name="password" >
<input type="submit" name="login">
</form>
</body>
</html>
When someone write the right password, he will go to this page
localhost:8080/test/login.php
but, if someone try to open "localhost:8080/test/login.php" directly, he will go to this page "localhost:8080/test/index.php".
this is my login.php code
<?php
session_start();
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else{
header('Location: /test/index.php/');
}
?>
test 1
Youve made several small mistakes (see comments), but the big mistake you make is that the session is never checked. Use this at login.php :
<?php
session_start();
if(!isset($_SESSION["valid"])){
header("location: index.php");
die();
}
?>
This checks if the session is set, and if not redirects back to index php

Unsetting multiple php pages

I have multiple pages in php. What i want is when you click the back button and you're logged out, that certain page will not display. Say, i clicked home, then logged out, display log in form and when back button on the browser is pressed, it will say you're logged out. I tried session destroy, clear cookies but it doesn't seem to work(or I'm doing it wrong). I am new to php and I am still in the process of learning it. Do you have any suggestions? O.O I have my code here:
here is my index.php
<?php
require 'core.inc.php';
if(isset($_SESSION['user'])&&!empty($_SESSION['user'])){
include 'home.php';
$html_block1 = "<script language='javascript'>
alert('Welcome');
</script> ";
echo $html_block1;
}else{
include 'loginform.inc.php';
}
?>
then my loginform
<?php
if (isset($_POST['user']) && isset($_POST['pass']) && !empty($_POST['user'])&& !empty($_POST['pass'])) {
$_username = $_POST['user'];
$_password = $_POST['pass'];
$_passwordhash = md5($_password);
$_file = 'password.txt';
$handle = fopen($_file,'r');
$_pass_from_file =fread($handle,1024);
trim($_pass_from_file);
if($_username == 'il' && ($_passwordhash == $_pass_from_file)){
$_SESSION ['user'] = $_username;
header('Location: index.php');
} else {
$html_block1 = "<script language='javascript'>
alert('Incorrect password');
</script> ";
echo $html_block1;
}
fclose($handle);
} else {
unset($_username);
}
?>
<form class="form" method ="POST" type="loginform.inc.php" >
<input type="text" placeholder="Username" name ="user" >
<input type="password" placeholder="Password" name = "pass" >
<input type = "submit" value = "Login">
<input type = "submit" value = "Change password" name = "change">
</form>
my core
<?php
ob_start();
session_start();
clearstatcache();
?>
home
<?php
echo 'Hi! you\'re home<br>';
echo 'please click link to next page<br>';
echo 'logout???';
?>
other page
<?php
echo "Hi<br>";
echo '<a href = logout.php>logout?</a>'
?>
and my log out
<?php
session_destroy();
header('Location: loginform.inc.php');
ob_flush();
?>
Suggestions or edits are welcome. Thanks a lot!

Echo'ing error message

We have a login page which validates the username and password from our database, however we'd like it to display the invalid username and password message above the input fields rather than at the top of the page. We know we can edit and put the php code in the div to display it where it is, we put out headers and therefore as soon as we move the php from the top of the page it generates an error message. Is there an alternative to this? Or a way of using the headers differently? Our code is below and an image of what we want...
<?php
error_reporting (E_ALL ^ E_NOTICE);
$username = $_POST['usrname'];
$pass_word = $_POST['pass_word'];
if(($usrname=="")&&($pass_word==""))
{
//Do nothing as nothing has been posted......
}
else
{
$con = mysql_connect("localhost"," "," ");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $con);
$result = mysql_query("SELECT * FROM `leicester_login` WHERE `user_name`='$username'", $con);
$num_row = mysql_num_rows($result);
}
if($username=="")
{
//do nothing as nothing has been posted
}
else
{
if($num_row == 0)
{
echo "<p>The username <b>". $username ."</b> doesnt exist!</p>";
}
else
{
$return_pass = mysql_fetch_array($result);
if($pass_word == $return_pass['pass_word'])
{
session_start();
if(isset($_SESSION['username']))
{
//do nothing as session already exists...
header("Location: ");
}
else
{
$_SESSION['username']= $username;
header("Location: ");
exit;
}
}
else
{
echo "<p>The password entered is incorrect!</p>";
}
}
}
?>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin">
<h2 class="form-signin-heading"><img src="" alt="Logo"/>Leicester</h2>
<?php
?>
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
<input type="password" name="pass_word" id="pass_word" class="input-block-level" placeholder="Password">
<center><button align="center" class="btn btn-large btn-primary" type="submit">Sign in</button></center>
< Go Back
</form>
</div> <!-- /container -->
</body>
</html>
Your if statement is wrong [There is no such $usrname variable on your code]
if(($usrname=="")&&($pass_word==""))
should be
if(($username=="")&&($pass_word==""))
Try this:
<?php
error_reporting (E_ALL ^ E_NOTICE);
$username = $_POST['usrname'];
$pass_word = $_POST['pass_word'];
if(($usrname=="")&&($pass_word==""))
{
//Do nothing as nothing has been posted......
}
else
{
$con = mysql_connect("localhost"," "," ");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $con);
$result = mysql_query("SELECT * FROM `leicester_login` WHERE `user_name`='$username'", $con);
$num_row = mysql_num_rows($result);
}
if($username=="")
{
//do nothing as nothing has been posted
}
else
{
$message = null; //create a container for the messages
if($num_row == 0)
{
$message = "<p>The username <b>". $username ."</b> doesnt exist!</p>";
}
else
{
$return_pass = mysql_fetch_array($result);
if($pass_word == $return_pass['pass_word'])
{
session_start();
if(isset($_SESSION['username']))
{
//do nothing as session already exists...
header("Location: ");
}
else
{
$_SESSION['username']= $username;
header("Location: ");
exit;
}
}
else
{
$message = "<p>The password entered is incorrect!</p>";
}
}
}
?>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin">
<h2 class="form-signin-heading"><img src="" alt="Logo"/>Leicester</h2>
<?php
//if there's something in the container, echo it out.
if (!is_null($message)) {
echo $message;
}
?>
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
<input type="password" name="pass_word" id="pass_word" class="input-block-level" placeholder="Password">
<center><button align="center" class="btn btn-large btn-primary" type="submit">Sign in</button></center>
< Go Back
</form>
</div> <!-- /container -->
</body>
</html>
Whenever echo is called it will output something right there, if it's before any output (like the html part), itt will show up before the HTML starts. If you put something in a container (like the $message) and output it with the html it will show up in the predestined place. As a side effect, the header("Location: "); will not throw headers already sent errors.
I recommend using Javascript:
If you place a span in the logindiv at the place you want. e.g. that span has an id of 'errormessage'. Now you can use Javascript to place the message in the span.
HTML:
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<span id="errormessage"></span>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
PHP:
//an error has occurred...
echo "<script>document.getElementById('errormessage').innerHTML='The password entered is incorrect!'</script>";
A benefit of using a span is that you can edit the layout of the errormessage using CSS.
I hope this is an answer to your question.
It's outputting it up top because that is where you are telling it to output - before the actual start of the HTML. One way to solve it is to save the string to display in a variable, and then display the variable at the proper place in your HTML.

get result in same page and form

hello i have simple problem with my functions there is 2 codes :
i need when i put the right input answer echo $row['answer']; and sucess in next code.
it means i need when $_POST['answer'] = $row['answer']; echo my password
can someone help me with if cond.
this code is working perfect :
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
$freeanswer = $row['answer'];
}
?>
code problem in same page :
</br>
</br>
<form action="" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
</div>
<?php
$anme = $_POST['answer'];
if ($anme==$freeanswer) {
echo "sucess";
} else {
echo "wrong";
}
?>
Do you have problem sending the data?
If you want to post the form data to the same page you could use this:
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post">
And this code will catch whatever you posted. (Put it in the same page as the form)
<?php
if(isset($_POST['answer'])) {;
if($name==$freeanswer) {
echo "success";
} else {
echo "wrong";
}
} else {
// Just for testing
var_dump("No data sent yet");
}
?>
Where is the $freeanswer variable declared in the second code?
This if statement is failing cause there is no $freeanswer declared.
$anme = $_POST['answer'];
if ($anme==$freeanswer) { ..
I see you declared it in first code but I dont see it in the second code..
EDIT :
Actually I didn't see It's all the same code. But still the problem is $freeanswer cause It's not declared in public scope It's only in the scope of while loop
Try declaring / writing this line of code here :
$username = $_POST['username']; // Near this line
$freeanswer = ""; // Declare this here
You should put a name to submit button, and the check the existence of $_POST['name_of_button'];
This is a dirty example I wrote quickly so you can get the idea, I didn't test it
<?php
// if the button has not been sent show the form
if(!isset($_POST['submit'])) {
?>
<form action="/test.php" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit" name="submit">
</form>
</div>
<?php
// otherwise means the form has been sent, show the password or wrong
} else {
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row) {
if($row['answer'] == $_POST['answer']) {
echo 'your password is ' . $row['password'];
} else {
echo 'wrong!';
}
}
}

Categories