Unsetting multiple php pages - php

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!

Related

PHP: session variable lost on clicking form submit button?

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!

I want users to update account information only after they log in... But I have no Idea How to do it

I have made simple php files by using which I can validate username and PASSWORD and then only user can log in. I want users to update account only if they log in to account. Without validating ID and password, they can't update their Name and Surname and all... It's very simple program. Here is the table Structure.
It is just a Demo data. I want users to update their accounts only after logging in. Here is the file by which they can see their information by logging in.
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
mysql_connect("localhost","adarsh","Yeah!");
mysql_select_db("aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
if($uname==$data['username'] && $pass==$data['pass'])
{
echo "<center>";
echo "Name: ".$data['username']."<br>";
echo "Last namme: ".$data['lastname']."<br>";
echo "<img src=".$data['image']."><br>";
echo "</center>";
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</html>
The code is working fine and They can see their data by entering username and password. If they will enter wrong Username and password, they will just see alert box.
I just want users to update their data after logging in. Without login, they can't update their data.
But i have no idea how to do it. Once I tried by validating username and password and then redirecting to new page where they can update their account using header location but that doesn't work. I didn't get any variables on the other page.
Help me solving this....
Try this
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
session_start();
if(isset($_POST["submit"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
if(empty($uname) && empty($pass))
{
echo "<script>alert('Empty');</script>";
}
else
{
mysql_connect("localhost","adarsh","Yeah!","aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
$count = count($data);
if(empty($count) || $count > 1)
{
echo "<script>alert('Invalid Login');</script>";
}
else
{
$image = $data['image'];
$lname = $data['lastname'];
$username = $data['username'];
$_SESSION["lastname"] = $lname;
$_SESSION["username"] = $username;
echo "Name: ".'$username'."<br>";
echo "Last namme:".'$lname'."<br>";
echo "<img src='$image'><br>";
if(isset($_SESSION))
{
redirect('new_page.php');
}
else
{
echo "<script>alert('Something Went Wrong');</script>";
}
}
}
}
?>
<form method="post" action="#">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>
and in new_page.php
<?php
session_start();
if(isset($_SESSION["username"]))
{
//show update form
}
else
{
//redirect to login page
redirect('login.php');
}
Includes
Using Session
Optimize Query
Validate all fields
and take a look at this too
How can I prevent SQL-injection in PHP?
MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
So, after logging in, instead of simply displaying the users details, display a form allowing the user to update their details, something like this (incomplete code just to give you an outline):
if($uname==$data['username'] && $pass==$data['pass'])
{
echo '<form method="" action ="">';
echo '<input value="'.$data['username'].'" />';
echo '<input value="'.$data['lastname'].'" />';
echo '<input type="submit" />';
echo "</form>";
}
If you want to pass variables from one page to another, once the user is logged in, you should use Session variables.
Thanks to all to answer on my question. Finally with the help of you guys, I solved every errors and Program is working fine!
I did this with the help of 2 files... Here are they,
updatedata.php (This file contains only html stuff... .html will also work)
<html>
<head>
<title>
Login
</title>
</head>
<body>
<form method="post" action="updateaccount.php">
Username : <input type="text" name="uname"><br>
Password :<input type="password" name="pass"><br>
New Information:<br><br>
New Name : <input type="text" name="newname"></input>
<input type="submit" name="submit" value="Update!">
</form>
</html>
updateaccount.php (hehe, Don't get confused in file names...)
<?php
$con=mysql_connect("localhost","adarsh","Password");
mysql_select_db("aadarsh",$con);
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
}
$sql="select * from users where username='$uname' AND pass='$pass'";
$select = mysql_query($sql);
$data = mysql_fetch_array($select);
$username=$_POST["newname"];
if(isset($_POST['submit']))
{
if($uname==$data['username'] && $pass==$data['pass'])
{
$user_id= $data['id'];
if(isset($_POST['newname']))
{
$update = mysql_query("UPDATE users SET username = '$username' WHERE id = $user_id");
if($update)
{
echo "<script>alert('updated!');</script>";
header("location:http://www.example.com");
}
else
{
echo mysql_error();
}
}
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
Thanks to all of you again.... :)
Some considerations about your code:
mysql_connect is deprecated, you should use mysqli_connect.
http://php.net/manual/en/book.mysqli.php
You can use empty() instead of isset(). empty() will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable. With !empty you can:
if (!empty($_POST["uname"]) && !empty($_POST["pass"])){
$uname = .........
}
Can't use echo and header("location:http....") in the same loop. If you send to another page, the message will not be displayed.
After a header("location:http....") you must exit(); otherwise, the code will follow the normal flow.
You check if ($update). If you click the submit button, $update always be true, so this check is not necessary.
Hope that helps.

PHPBB login script

after playing around with the script from all the help you people have given me I have come over another problem, when i click login on the login form it says: The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Now i do admit i am no script pro but this is the only script i can find on how to use a phpbb forum database on a external site. so my question is whats wrong with all the .php file i am about to show you and how can i repair them?
login.php
<?php
//ob
ob_start();
//session
session_start();
if (isset($_SESSION['username']))
{
header("Location: main.php");
exit();
}
//connect
$error = 'Zaoby Database ERROR! connection failture!';
mysql_connect('localhost','root','') or die ($error);
mysql_select_db('phpbbtest') or die($error);
//include functions.php php script
require 'forums/includes/functions.php';
if (isset($_POST['login']))
{
//get form data
$username = addslashes(strip_tags(strtolower($_POST['username'])));
$password = addslashes(strip_tags($_POST['password']));
if (!$username||!$password)
echo "please enter a username and password<p />";
else
{
//find username
$find = mysql_query("SELECT * FROM phpbb_users WHERE username_clean='$username'");
if (mysql_num_rows($find)==0)
echo "username not found<p />";
else
{
while ($find_row = mysql_fetch_assoc($find))
{
// grab password hash for user
$password_hash = $find_row['user_password'];
}
$check = phpbb_check_hash($password, $password_hash);
if ($check==FALSE)
echo "Incorrect password<p />";
else if ($check==TRUE)
{
$_SESSION['username']=$username;
header("Location: main.php");
exit();
}
}
}
}
?>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p />
<input type="submit" name="login" value="Log in">
</form>
main.php
<?php
//ob
ob_start();
//session
session_start();
$session_username = $_SESSION['username'];
if (!isset($_session_username))
{
header("Location: login.php");
exit();
}
else
{
echo "hello, ".$_session_username." <a href='logout.php'>Log out</a>";
}
ob_end_flush();
?>
logout.php
<?php
session_start();
session_destroy();
header("Location: login.php")
?>
P.S someone in my last question about this put something about using MySQLi instead of mysql_query and that i should put a ob_end_flush somewhere?
Try to use ob_start(); just after the
e.g. <?php ob_start();

Session Handling in PHP 5

i've a problem with php session handling that i can't explain to myself.
I'm studying php from scratch, and i can't figure out how to mantain a session live:
This is my index page, where a user can login or register to the database visiting the right page, and then come back to see if he's logged in:
Code:
Index
<?php session_start(); ?>
Register
Login
<?php
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin'];
?>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
else
{
echo "Please Register or Login";
}
?>
In fact this work, because when i come back from login.php it says, "Logged as: Admin"
But when i click on the link to get the login page, or register page again from the index page, i should get the same message, "Logged as...", but the session appear to be closed instead. :(
here's login.php:
<?php
session_start();
include "dbConnect.php";
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin']; // IT NEVER SHOW THIS MESSAGE
}
if(isset($_POST['submit']) &&(trim($_POST['submit']) == "Login"))
{
if(!isset($_POST['user']) || $_POST['user']=="")
{
echo "Attenzione inserire l'username.";
}
elseif(!isset($_POST['pwd'])||$_POST['pwd']=="")
{
echo "Attenzione inserire la password.";
}
else
{
$u = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));
$u = str_replace(" ","_",$u);
$p = trim(filter_var($_POST['pwd'], FILTER_SANITIZE_STRING));
$p = sha1($p);
$istance = new dbHandle;
$istance->connect();
$data = $istance->query("SELECT * FROM login WHERE username_login = '$u' AND password_login = '$p'");
if(mysql_num_rows($data) == 0)
{
echo "Failed";
echo "<a href='index.php' target='_self'> Go Back </a>";
}
else
{
echo "Logged";
$res = $istance->getdata($data);
$_SESSION['login'] = $res->id_login;
$_SESSION['nlogin'] = $res->username_login;
echo "<a href='index.php' target='_self'> Go Back </a>";
}
}
}
else
{
?>
Login
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input name="user" type="text" size="20" required="required"/>
...
<input name="pwd" type="password" size="20" required="required"/>
...
<input type="submit" name="submit" value="Login"/>
</form>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
$istance->disconnect();
?>
When i come back using the link above "Go Back" to the index page, it shows Logged as...
but when i come back here again, it does not.
So i assume my session were destroyed automatically? but why?
Thanks, i appreciate your help.
I forget to say that PHP.ini has
session.cookie_lifetime
set to "0"
Thanks
You are calling unset($_SESSION['login']) many times. It removes your login:
<form method="post" action="<?php unset($_SESSION['login']) ?>">
Try this:
<form method="post" action="index.php">
<input type="button" name="logOut" value="LogOut" />
</form>
<? if (isset($_REQUEST['logOut'])){ session_destroy(); } ?>
unset the session like below
if(isset($_REQUEST['logOut']))
{
unset($_SESSION['login']);
}
You check for if(isset($_SESSION['login'])).
If that results in true, you do <form method="post" action="<?php unset($_SESSION['login']) ?>">
Note the unset($_SESSION['login']) part - after that, if(isset($_SESSION['login'])) will return false.
Session overview :
<?php
// Always Start our session
session_start();
$_SESSION['username'] = 'Saurabh Singh';
$username = $_SESSION['username'];
echo $username;
if(isset($_SESSION['username']))
{
Do your action
}
else
{
echo "Please Register or Login";
}
I don't think the session has been destroyed!
I would start by first removing all the empty lines between the opening tags for php and the
session_start().
Test it again and you could add the line
error_reporting(E_ALL);
below the session_start to see if any error messages are echo(ed) back to you.
In your PHP.ini what
session.cookie_lifetime = 0
means is that the session remain active so long as the browser stays open. It's only destroyed when the browser is closed.
I hope this helps

cant make login page work

I have this php page that posts to itself and then it checks weather if to login someone or not. The problem I am having is that if it logins... then it still shows the username and password textboxes.. but if i refresh they go away and now the welcome thing comes up thanks to the session.
What i want is to once the submit is clicked and it logs the person in to immediately not show the textboxes (username, password) and show the welcome message. Right now i have to refresh.
Please note i am new to PHP and any wise advise will be much appreciated.
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
?>
Problem here is just your code is not in sequence. I have corrected Try it now.
<?php
session_start();
echo "<body>";
//Start session
//print_r($_SESSION);exit;
//Check whether the session variable SESS_MEMBER_ID is present or not
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
if(isset($_POST))
{
$login_query = "SELECT reg_id, role_id, f_name FROM registration WHERE f_name = '$_POST[logInUsername]' AND password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("sunlinux","pukhraj","pukhraj123")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("testbaj", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["f_name"];
$userrole = $row["role"];
$userid = $row["reg_id"];
}
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
}
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
//Write session to disc
session_write_close();
echo "<form method=\"post\" ><div id=\"login\" class=\"login\">
<label for=\"login\">User Name</label>
<input type=\"text\" name=\"logInUsername\" />
<label for=\"Password\">Password</label>
<input type=\"password\" name=\"logInPassword\" />
<input type=\"submit\" value=\"Submit\" class=\"button\" />
</div>";
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo "<div id=\"login\" class=\"login\">
<label for=\"welcome\">Welcome '$sessionName' !</label>
</div>";
}
?>
Small changes :
Just plase form tag at appropriate place.
Never mix code after post and before post.
here all database stuff should be execute after submit so I enclosed them in condition if(isset($_POST))
due to nonlinearity of code it was creating session after one more refresh after post data. Now corrected.
for message :
do below changes :
give name to submit button <input type=\"submit\" name=\"submit\" value=\"Submit\" class=\"button\" />
replace first if condition with if(isset($_POST['submit']))
So, not dealing with any of the security or style issues that are here...
Right now you are seeing if the session is set. If it is not, then you process the login. After processing the login, you display the form fields.
You should actually check for 3 states...
Is someone already logged in?
Do you need to process a login?
If neither of those, show normal form...
You can do this by using your existing isset for the session field.
Then if it is not set, check if the post fields are set... if they are set, process a login.
Otherwise, show the basic login form.
EDIT:
Full code sample (sorry for the terrible formatting, mostly cut and paste...:
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) != '')) {
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else if ($_POST[logInPassword] != null && $_POST[logInUsername] != null)
{
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else
{
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
?>
Good luck!
Your logic just needs to be rethought. How about something like this? (pseduocode)
if( user is NOT logged in) // Check via session
{
$errors = array();
if( user submitted the form and is trying to log in) // Can be checked with a POST'd variable
{
// Set the session correctly here, query DB, etc.
// If there are any errors, add them to the $error array
}
if( !empty( $errors) || form was not submitted)
{
// Print the form and any errors (like invalid username / password combo)
}
exit; // Stop here
}
// Print welcome message here (since we know if we get here, the user is logged in)

Categories