php sessions are not being saved - php

I apologize for the wall of text but I've been banging my head against the wall around this problem for awhile so I'm gonna try to provide as much information as possible.
I'm not quite sure if the problem I'm getting has to do with user sessions (I'm new to PHP), but that's what it seems to me.
I ask a user to enter his login information (id and password) to enter the system in ask_login.php:
<div class="login_box">
<h1>Login</h1>
<form method="POST" action="login.php">
<p><input type="text" name="username" placeholder="UserID"></p>
<p><input type="password" name="password" placeholder="Password"></p>
<input type="submit" name="submit" value="Login"></p>
</form>
</div>
If the login details (id and password) are found in the database the user gets logged in to his user portal (login.php) where he can check his details, exams dates, etc..
My problem is whenever I login, if I click for example on the details button to check the user details, it redirects me to my ask_login.php page asking for my login details again saying that I didn't enter any ID/Password details.
I've tried removing the code where it checks if the login forms were submitted blank, and it eventually started working and I was able to click the 'Details' button or any other button, without getting redirected to ask_login.php.
But now when I click on the 'Details' button my "Welcome, username" line doesn't show the username, which makes me think that it has something to do with php sessions. Furthermore, any query that I make won't show the result.
Here's my login.php code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Logged in | FCUL</title>
<link rel="stylesheet" href="css/stylesheet_loggedin.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="shortcut icon" href="img/vitor-20130904-favicon.ico"/>
</head>
<body>
<div id="header">
<br/>
<img src="/img/fcul_cent_logo_001.png" width="510" height="70"/>
</div>
<div id="loggedinas">
<br/>
Welcome,
<?php
$result = mysql_query("SELECT nome FROM users WHERE id='$username'");
while($row = mysql_fetch_assoc($result)) {
echo $row["nome"];
}
?>
( <?php echo $username; ?> )
<br/>
<div id="logout">
<font size="2"><u>[Logout]</u></font></a>
</div>
<hr/>
</div>
<?php
//FETCH USER'S BI
if(isset($_POST['username'] )) {
$ID = $_REQUEST['username'];
$query = "SELECT bi FROM users WHERE id='$ID'";
//if query is successful
if($query_run = mysql_query($query)) {
//if it returns 0 rows
if(mysql_num_rows($query_run)==NULL) {
echo "<script>alert('Unexpected Error 004');</script>";
echo "<script language='javascript'>window.location = 'index.php';</script>";
}
while($query_row = mysql_fetch_assoc($query_run)) {
$bi = $query_row['bi'];
//echo $bi;
}
}
}
?>
<br/>
<center>
<div id="buttons">
<form method="POST" action="login.php">
<input type="submit" name="details" value="details">
</form>
<?php
//**print user's BI if he clicks on 'Details' button**
if($_POST['detalhes']){
echo '<div id="content">' . $bi . '</div>';
}
?>
</div>
</center>
</body>
</html>

you cannot access session on first time you insert it in $_SESSION['id'] = $username variable.
you can only access it on the second run of session_start();
try this.
1. make login.php
2. make welcome.php
try to separate the module where login.php will only process for checking
the login process then if this condition success then
<?
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
$_SESSION['id'] = $username;
header("location: welcome.php");
}
?>
in welcome.php
<?
session_start();
// this is for the checking if user is loged in
if (!$_SESSION['id']) {
header("location: ask_login.php");
exit;
}
?>

You are not checking if the user is already logged, so, after receiving your post from ask_login.php, when you click anything in your page $username and $userpassword will be null.
Just wrap all your code after session_start with
if($_SESSION['id'] === false)
{
//Your code
$username = $_POST['username'];
$password = $_POST['password'];
if($username &&...
}

wrap your code with this
if ($_SESSION['id']){
//your login checking here
};
e.g
if ($_SESSION['id']){
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
}
?>

Related

Current Logged in user/admin must not delete itself (which's currently logged in)

I have a 'users' table which have two columns/attributes i-e username and password. this table holds admins of the website. now i have created a form that's used to delete one or more admins from the table mentioned above, but if currently logged in user tries to delete itself, it must not happen.
the problem i'm facing is: i have received the username and password of the currently logged in user from the session, but when i enters another admin details, still it gives me the error that currently logged in user is trying to delete itself.
FORM:
<form action="delete_user.php" method="post">
<fieldset><legend style="text-align:center; font-size:18px">Enter Details of the User You want to Delete</legend><br>
<label for="username">Username : </label><input type="text" name="username" placeholder = "Username"><br>
<label for="password">Password :</label><input type="password" name="password" placeholder = "Password"><br>
</fieldset>
<p id="btn">
<input type="submit" value="Delete" name="submit_delete_user" style="font-size:16px"><input type="reset" value="Reset" style="font-size:16px"><br>
<center>
Admin Home<br>
Logout
</center>
</p>
</form>
PHP file/CODE:
<?php session_start();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Connection Error: " . mysqli_connect_error();
}
//reiving values from form
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
if(isset($_POST['submit_delete_user'])){
if(!empty($_POST['username']) && !empty($_POST['password'])){
if($username == $_SESSION['username'] && $password == $_SESSION['password']){
$sql_delete = "DELETE FROM 'users' WHERE username = '$username' AND password = '$password'";
if($result = mysqli_query($con, $sql)){
echo '<script language="javascript" type="text/javascript">
alert("Record Deleted Successfully!");
window.location = "admin.php";
</script>';
}else { echo '<script language="javascript" type="text/javascript">
alert("SQL Error!");
window.location = "delete_user_form.php";
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Sorry! You can not delete currently Logged in User");
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Please Fill the Form Completly");
window.location = "delete_user_form.php";
</script>'; }
}
?>
LOGIN (from where i'm getting currently logged in user details)
<?php session_start();
error_reporting();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno()){
echo "Connection Error: " . mysqli_connect_error();
}
mysqli_select_db($con,"camouflage_studio");
if(isset($_POST['submit_login']))
{
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$get_user_name = mysqli_real_escape_string($con,$_POST['username']);
$get_password = mysqli_real_escape_string($con,$_POST['password']);
$sql = "SELECT * FROM `users` WHERE username='$get_user_name' and password='$get_password'";
if($result = mysqli_query($con, $sql))
{
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $get_user_name;
$_SESSION['password'] = $get_password;
header('Location:admin.php');
}
else{
header('Location:login_form.html');
}
}
else{
header('Location:login_form.html');
}
}
else {
header('Location:login_form.html');
}
}
?>
I think your if condition is opposite :
Try this :
if($username != $_SESSION['username']){
// delete user
} else {
// can not delete
}

Trying to create login page using PHP and SQL

I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.

staying in same page after submiting form button

I'm trying to stay on the same page after submitting a form button.
Depending on the button the user clicks, I want to display certain information on that same page the button was clicked.
For some reason it keeps redirecting me back to my "ask_login.php" page after I click on the button.
I've read around and some people recommend using AJAX or JQuery but I don't really understand much about it. I'd be appreciated if I could get some help. Thanks.
loggedin.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
<form action="#">. no action means 'submit to current url', the pound sign mean 'the current document' and should not navigate. though i'm not sure forms semantically allow this.
I would recommend posting the form data over ajax though. Its not hard to do, Jquery offers the most used ajax function and you basically loop though each input in a form and push the value into a uri-encoded string and post that via an ajax call.
I think this following code is not correct...
if($username && $password)
Try this
if(!empty($username) && !empty($password))
i think it shout be
<?php
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
you can use jquery to process the form
$.post( "test.php", $( "#testform" ).serialize(),function(e){alert(e);} );
test.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
http://api.jquery.com/jquery.post/
beware, no input validation!
read this page
http://www.php.net/manual/en/function.mysql-real-escape-string.php

Log in page on index.html

I currently have a login system on my index page; which is working fine. However, when a user logs in, it directs them to a completely new page which i don't want. How to I implement the code so that;
A) the user stays on the index page after login
B) A welcome message "Welcome...." displays on the index page.
index.html
<div id="leftmenu_top"></div>
<div id="leftmenu_main">
<div class="login">
<h3>Please login below</h3>
<br/>
<!--Log in form-->
<html>
<form action='login.php' method='POST'>
Username: <input type='text' name='username'><br>
Password: <input type='password' name='password'><br>
<input type='submit' value='Log in'>
</form>
</html>
login.php
<?php
session_start();
$username = strtolower($_POST['username']);
$password = strtolower($_POST['password']);
if ($username&&$password)
{
$connect = mysql_connect("localhost", "root", "") or die("Couldn't connect");
mysql_select_db("a&e") or die("Couldn't find db");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows==!0)
{
//code to login
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//check to see if they match
if($username==$dbusername&&$password==$password)
{
echo "Welcome $username";
$_SESSION['username']=$username;
}
else
echo "incorrect password";
}
else
die("That user does not exist");
}
else
die("please provide a username and password");
?>
put
header('Location: index.php');
at the bottom of the login.php
Also, if you add ?success at the end of this link and then call it in your index page it will display the message you want. Change the above code to
header('Location: index.php?status=success');
and then in you index page put this where you want the message to appear
<?php If($_GET['status'] = "success") { ?>
<p>This is a welcome message</p>
<?php } ?>
<?php if(isset($_POST['submit'])){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = "SELECT Username, Password FROM tbluser
WHERE Username = '$username' AND Password = '$password'";
$result = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($result) == 0){
echo ' Password/Username is not found';
}else {
while($row = mysql_fetch_array($result)) {
echo 'You are logged in </br>';
}
}
}

Login form not submitting properly in PHP

I'm new to PHP and I have a login page with a form. I want to authenticate the user and then redirect the user to another page with the season values. When I submit the page is not redirecting and if a pres F5 the page will popup the resubmission message of the form. This is my code.
<?php
session_start();
include('../includes/header.php');
$title="Login";
?>
<?php
include('../includes/authenticate.php');
include('../includes/dbschema.php');
//if the user has not logged in
if(!isLoggedIn())
{
if($_SERVER['REQUEST_METHOD']== 'POST'){
//include('../includes/authenticate.php');
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if(isset($_POST['username']) && isset($_POST['password'])){
$query = "SELECT password, salt FROM user WHERE username = '$username';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
header('login.php');
$errmessage = "Invalid user";
print "<p id\"errmessage\"> $errmessage </p>";
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('login.php');
}
else
{
validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: actividades.php');
}
}
else
{
$status = "logout";
print "<p id=\"usernamelink\">Bienvenido,<a id=\"usernamecolor\"> " . $_SESSION['username'] . " </a></p>";
print "<a id=\"logoutlink\" href=\"../includes/logout.php \">Log out</a>";
//page content follows
}
?>
</br>
<div id="logindiv">
<?php print "<h1 id=\"logintitle\">Login</h1>";?>
<form id="loginform" name="login" action="login.php" method="post" >
Username: <input id="inplogin" type="text" name="username" />
<br/><br/>
Password: <input id="inplogin" type="password" name="password" />
<br/>
<input id="btnlogin" type="submit" value="Login" />
</form>
</div>
<?php include('../includes/footer.php') ; ?>
You should exit; after redirecting. And pass the error to your login script, for example:
if(login_fails()){
header('Location: login.php?errorCode=1');
exit;
}
In your login.php script, check if $_GET['errorCode'] is present and display an error message:
$errors = array(
1 => 'Incorrect password',
);
if(isset($_GET['errorCode'])){
$code = $_GET['errorCode'];
print isset($errors[$code]) ? $errors[$code] : 'Unknown error';
}

Categories