Simple PHP Session variables - php

I can't figure out why the following PHP won't work properly:
<?php
//Authenticate user credentials
function authenticate($name, $password) {
$sql = "SELECT *
FROM users
WHERE username = '$name'
AND password = '" . md5($password) . "'";
$result = mysql_query($sql);
if ($row = mysql_fetch_array($result)) {
//Successful login
echo "Welcome back, " . $row['username'] . "!";
return true;
} else {
//Failed login
echo "Invalid username or password";
return false;
}
}
function addUser($name, $password) {
$sql = "INSERT
INTO users (username, role, password)
VALUES ('$name', 'CHAIR', '". md5($password) . "');";
mysql_query($sql);
}
function createTables() {
$sql = "CREATE TABLE Users (
Create table Users(
username varchar(50) NOT NULL,
role ENUM('CHAIR', 'FACULTY', 'STAFF') NOT NULL,
password varchar(255) NOT NULL,
email varchar(50) NOT NULL PRIMARY KEY,
applicant_client_id varchar(50) NOT NULL,
countries varchar(50),
research_area varchar(255),
numAssignedReviews TINYINT UNSIGNED,
available varchar(50),
workload FLOAT UNSIGNED
);"
;
mysql_query($sql);
}
session_start();
if (isset($_SESSION['loggedIn'])) {
echo '<script> alert("LoggedIn is set") </script>';
$con = mysql_connect("localhost", "ttony21_Tony", "cse308");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ttony21_GARS", $con);
$name = $_POST["name"];
$password = $_POST["password"];
if (authenticate($name, $password)) {
$_SESSION['loggedIn'] = true;
}
mysql_close($con);
} else {
$_SESSION['loggedIn'] = false;
echo '<script> alert("LoggedIn is not set") </script>';
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>GARS</title>
<style type="text/css">
body {
text-align: center;
min-width: 600px;
}
#wrapper {
margin: 0 auto;
width: 600px;
text-align: left;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div class = "wrapper">
<?php
if ($_SESSION['loggedIn']) {
echo '
<div class = "upload">
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
';
} else {
echo '
<div class = "login">
<form action = "/" id = "loginForm" method = "post">
<p>
Username: <input type = "text" name = "name" />
<br />
Password: <input type = "password" name = "password" />
<br />
<input type = "submit" id= "submit"/>
</p>
</form>
</div>
';
}
?>
</div>
</body>
</html>
There's a form: <form action = "/" id = "loginForm" method = "post">
When I either submit the form, or refresh the page, it should alert me with the message "LoggedIn is set" correct? But I only get the message "LoggedIn is not set."
I know that the session starts and the loggedIn is set properly, but I seem to lose the variable when I refresh the page or use the form, which shouldn't happen because it's a session variable right?
I'm new to using them so any help would be appreciated.

Session_Start() should be before the if statement, not in the else part.
<?php
session_start();
if (isset($_SESSION['loggedIn'])) {
echo '<script> alert("LoggedIn is set") </script>';
...
} else {
$_SESSION['loggedIn'] = false;
echo '<script> alert("LoggedIn is not set") </script>';
}
?>
I would slightly modify that to clarify that session_start() should be at the very beginning of the page, before any HTML is output. Once HTML has been output, a session won't start.

If you want to read the $_SESSION global, you must have started a session. i.e session_start(); must have been called. When logging in you might need to start it two times: once for the validation of the user and doing something like $_SESSION['status'] = 'authorized'; Then generally you create a redirect with header('Location : somewhere'); I am no professional on the header() function, but I know that after it you must do session_start() again if you want to read from the $_SESSION global variable.

From http://php.net/manual/en/function.session-start.php
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
So you need call session_start every request.

Related

How to validate the login form with 3 filelds?

I am able to validate the login form with 2 fields such as username and password.But I need to add other field called customer id.this. I need to pass this customer id next php page . there I have to store this in a variable. I am able to do all this.
But my problem is I am not able to validate after adding customer field. Because here I am passing the customer id after he enters in the text box.
When I add 2 fields I am able to validate.
how to validate this.
My code is,
Login.php
<!DOCTYPE html>
<html>
<head background-color:blue>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/style1.css">
<style>
p{
color:white;
font-size:26px;
font-weight: bold;
}
label{
color:black;
font-size:13px;
font-weight: bold;
}
h1{
font-weight: bold;
}
</style>
</head>
<body>
<section class="container">
<div class="login">
<h1><font color ="MAROON">Login to Merahkee Tech solutions</font></h1>
<form action = "site.php" method = "post">
<label> Username :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label> Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<label> Custoner ID :</label><input type = "password" name = "custid" class = "box" /><br/><br />
<input type = "submit" value = "Login "/><br />
</form>
</div>
</body>
</section>
</html>
<?php
include("Config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$sql = "select user_table.user_id,username,`password`,cust_id from user_table join customer_table on customer_table.user_id=user_table.user_id where username = '$username' and BINARY password = '$password';";
$result = mysqli_query($db,$sql);
if (!$result) {
printf("unable to connrct to database");
exit();
}
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['login_user'] = "";
//header("location:http://localhost/Dashboard/TreeStructure/fr1.php");
}
//username field empty
elseif($username==null){
$error="SELECT Message FROM error_message WHERE id=1";
$ren = mysqli_query($db,$error);
$row = mysqli_fetch_array($ren);
$to =$row['Message'];
echo '<script type="text/javascript">alert(" ' . $to . ' ");</script>';
}
//password field empty
elseif($password==null){
$error2="SELECT Message FROM error_message WHERE id=3";
$ren2 = mysqli_query($db,$error2);
$row2 = mysqli_fetch_array($ren2);
$to2 =$row2['Message'];
echo '<script type="text/javascript">alert(" ' . $to2 . ' ");</script>';
}
//SPACE WHILE ENTERING USERNAME
elseif(preg_match('/\s/', $username)){
$error1="SELECT Message FROM error_message WHERE id=2";
$ren1 = mysqli_query($db,$error1);
$row1 = mysqli_fetch_array($ren1);
$to1 =$row1['Message'];
echo '<script type="text/javascript">alert(" ' . $to1 . ' ");</script>';
}
//SPACE WHILE ENTERING PASSWORD
elseif($num!=0){
$error3="SELECT Message FROM error_message WHERE id=5;";
$ren3 = mysqli_query($db,$error3);
$row3 = mysqli_fetch_array($ren3);
$to3 =$row3['Message'];
echo '<script type="text/javascript">alert(" '. $to3 .' ");</script>';
}
elseif($num1!=0){
$error5="SELECT Message FROM error_message WHERE id=4;";
$ren5 = mysqli_query($db,$error5);
$row5 = mysqli_fetch_array($ren5);
$to5 =$row5['Message'];
echo '<script type="text/javascript">alert(" '. $to5 .' ");</script>';
}
//WRONG USERNAME AND PASSWORD
else{
$error4="SELECT Message FROM error_message WHERE id=6;";
$ren4 = mysqli_query($db,$error4);
$row4 = mysqli_fetch_array($ren4);
$to4 =$row4['Message'];
echo '<script type="text/javascript">alert(" ' . $to4 . ' ");</script>';
}
//space while entering username
}
?>
In site.php
<!DOCTYPE html>
<html>
<head>
<title>Merahkee Tech Solutions </title>
<link rel="stylesheet" href="php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2> Select Project</h2>
<?php
$m=$_POST['custid'];
include("Config.php");
$cust_id ="select project_name from customer_access where customer_id=$m;";
$ren = mysqli_query($db,$cust_id );
while($row=mysqli_fetch_array($ren)){
echo'<form action="right.php" method="post">
<label class="heading">Select Your Project:</label><br>
<input type="checkbox" name="check_list[]" value='.$m.'><label>'.$row['project_name'].'</label><br>
<input type="submit" name="submit" Value="Submit"/>
</form>';
}
?>
</div>
</div>
</body>
</html>
In right.php
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo " $checked_count <br/>";
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
}
}
else{
echo "<b>Select Atleast One Option.</b>";
}
}
?>
Can Anybody help me to solve this.
In login page I have tried this. But I did not get.
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$cust_id = mysqli_real_escape_string($db,$_POST['cust_id']);
$sql = "select user_table.user_id,username,`password`,cust_id from user_table join customer_table on customer_table.user_id=user_table.user_id where username = '$username' and BINARY password = '$password' and cust_is="$cust_id" ;";
$result = mysqli_query($db,$sql);
if (!$result) {
printf("unable to connrct to database");
exit();
}
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['login_user'] = "$cust_id";
header("location:http://localhost/Dashboard/TreeStructure/fr1.php");
}
I tried to print this, after login.It prints username and password but not cust_id.
It prints username and password but not cust_id
You are not running the code you have shown us.
The SQL statement has at least two fatal error.
select user_table.user_id,username,`password`,cust_id
from user_table
join customer_table
on customer_table.user_id=user_table.user_id
where username = '$username'
and BINARY password = '$password'
and cust_is="$cust_id" ;
You are using double quotes around $cust_id in the where clause - this should be single quotes. You are trying to match this value to an attribute named cust_is - don't you mean cust_id?
The code you have shown us will fail to match a login each time.
It also seems very strange to use a customer id as an authenticator/identifier when you already have the identifier (username) and authenticator (password) and can derive the vustomer id from the database at login.

How to verify user details using PHP by retrieving data from SQLite3 database?

I am new to PHP coding. I have created two forms. One is for signing up and the other for logging in. Unfortunately both fail to work due to some issues in the queries. I also searched and went through similar posts on this site but none solved my problem. I want to verify whether a user with the same id exists in the database "Users.db" at the time of signing up if any user enters the same id he should be notified to enter a valid id.
When I run my "sign in.php" code, it displays the following message on the screen without even waiting for the user to press the submit button/ sign up button.. "Number of rows found: 1 .This id is not available. Please enter a valid id." This message gets displayed even if the user enters a unique id that doesnt exist in the database before. Nothing gets stored in my database even if the id is unique by pressing the sign up button.
Secondly while logging in, the id and password entered by the user must be verified and matched with those stored in the database. He should be directed to the "index.html" page after successfully login in and only if he has signed up before. He should also be able to view his search history that is stored in "Search" table in the same database. This table contains two columns. One for the User id and the other for saving his search results.
The Search table looks like:
Id | History
nl23 Grand Hayat Hotel
Pearls Residencia Hotels
I am getting this error after running my code for login form "Unable to prepare statement: 1, near "AND": syntax error in D:\log in.php on line 54".
My log in form code is below:
log in.php
<body>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['uid'])) {
$id = $_POST['uid'];
}
if (isset($_POST['passid'])) {
$pass = $_POST['passid'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
?>
</body>
</html>
My sign in form is below:
sign in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
// $ret = $db->query($result);
//$ret = $db->exec($sql);
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
?>
</body>
</html>
Please guide me as i am stuck in both these codes.
What you are missing is checking if $_POST is set or is not empty. Only then you want to process user input. One more thing is that you should wrap $pass in quotes as it is a string and will be interpreted as column name if not surrounded with quotes.
Here's code:
log in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$pass = $_POST['Password'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
}
?>
</body>
</html>
sign in.php:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
}
?>
</body>
</html>

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.

Session doesn't start when correct login credentials are given

Alright, SO. After about five hours of sifting through potential duplicates and applying would-be solutions to my project and even downloading a PHP IDE to make sure that my syntax is all nice and tidy for everyone.. I am finally at the point where I need some advice.
My two problems (which may be related):
When someone logs in, successfully with the test parameters I have stored in the DB, they are not redirected (maybe my if statement is not correct?)
When the page loads without first attempt, my "wrong password - username combination" message is displaying. I'm fairly certain as to why but not too sure how to fix it.
<?php session_start(); // this line of code has been added by the instruction of a comment.
if(isset($submit)) {
$username = $_POST['username'];
$password = $_POST['password'];
}
$con = mysqli_connect("***","***","***","***");
$S_username = mysqli_real_escape_string($con, $username);
$S_password = mysqli_real_escape_string($con, $password);
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$S_username' AND `password` = '$S_password'");
if(!$sql) {
die(mysqli_error($con)) ;
}
$check_again = mysqli_num_rows($sql);
if($check_again == 1) {
session_start(); // this line of code has been deleted
$_SESSION['logged in'] = TRUE;
$_SESSION['username'] = $S_username;
header("Location: http://terrythetutor.com/submitvideo.php");
}
else {
echo "Your username and password combination was not recognised. Please try again." ;
}
?>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php include_once 'googleanalytics.php'; ?>
<body>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<h1 align="center">Please login to access restricted files</h1>
</br>
</br>
</br>
</br>
<div align="center">
<form action = "login.php" method = "post">
Username: <input type = "text" name = "username"></br></br>
Password: <input type = "password" name = "password"></br></br>
<input type = "submit" value = "Login" name="submit">
</form>
</div>
</body>
</html>
Any and all feedback is welcomed. Thank you.
use session_start(); only once and at the top ..

How do I use SESSION_START to keep a user logged into my website

So I'm trying to make a website but I'm stuck on the login no matter what I try I login go to the home page and immediately get logged out please help I really want to get this website up and running by the end of next year
login.php
<?php
SESSION_START();
$_SESSION['uname'] = $uname; // Set the user's name.
require('config.php');
if(isset($_POST['submit'])){
$uname = mysql_escape_string($_POST['uname']);
$pass = mysql_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname' AND `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
header("Location: home.php");
echo "You are now logged in.";
exit();
}else{
echo "Wrong username and password combination.";
}
}else{
$form = <<<EOT
<form action = "login.php" method = "POST">
Username: <input type = "text" name="uname"> <br />
Password: <input type = "password" name = "pass" /> <br />
<input type = "submit" name = "submit" value = "Login"/>
</form>
EOT;
}
echo $form;
?>e
Home.php
<?php
SESSION_START();
$_SESSION['uname'] = $uname; // Set the user's name.
if($uname){
echo $uname;
}
?>
<?php
if(!$uname){
?>
Register
Login
<?php
}
?>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>ArcheWorlds</title>
</head>
<body bgcolor="black">
<div class = "HomeNav">
Register<!--class = "HomeNavButton"-->
|
Login
</div>
<p>Hello and welcome to Archeworlds!</p>
</body>
<div class="footer" style="border-top: 1px solid #FFFFFF padding-bottom: 10px margin-top: 150px"> <img `src="Pictures/Studio 8 (small).png">`
login_form.php
<?php
session_start();
if (isset($_SESSION['uname'])) {
$username = $_SESSION['uname'];
echo $username;
exit(); # Ready to go!
}
?>
<form action = "login.php" method = "POST">
Username: <input type = "text" name="uname"> <br />
Password: <input type = "password" name = "pass" /> <br />
<input type = "submit" name = "submit" value = "Login"/>
</form>
login.php
<?php
session_start();
$username = mysql_escape_string($_POST['uname']);
$pass = md5(mysql_escape_string($_POST['pass'])); ## This is *INCREDIBLY* insecure
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname' AND `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
$_SESSION['uname'] = $username;
header("Location: home.php"); # Ready to go!
exit();
}
else {
header('login_form.php'); # Failed
}
The simplest way to come up with a more secure password hash is to generate a salt for the database and then come up with an implementation of PBKDF2 using the PHP Manual Page for it
I think you need to make few changes in code: login.php
<?php
if( isset( $_GET['action'] ) && $_GET['action'] == "logout") {
session_unset();
}
if(isset($_POST['submit'])){
SESSION_START();
$_SESSION['uname'] = $_POST['uname']; // Set the user's name.
require('config.php');
$uname = mysql_escape_string($_POST['uname']);
$pass = mysql_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname' AND `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
header("Location: Home.php");
exit();
}else{
echo "Wrong username and password combination.";
}
} ?>
& Home.php will be like :
<?php
if( false == isset( $_SESSION['uname'] ) ) {
header("Location: login.php");
exit();
} ?>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>ArcheWorlds</title>
</head>
<body bgcolor="black">
<div class = "HomeNav">
Register|Logout
</div>
<p>Hello and welcome to Archeworlds!</p>
<div class="footer" style="border-top: 1px solid #FFFFFF padding-bottom: 10px margin-top: 150px"> <img src="Pictures/Studio 8 (small).png">
</body>
Note: I haven't tested this code, But will work for you.
I recommend you to study this. http://www.homeandlearn.co.uk/php/php14p1.html. they have examples on Login Database with sessions for users..

Categories