I've been working on a project that has to do with renting houses. Visitors can register or log-in, and only logged-in users can Add a house for rental. Each user has his own profile showing his username, email and accommodations he has uploaded for rental.
My problem is that I cannot retrieve the email of the logged in user. Also, on my MySQL DB I'm using a foreign key in my accom(modation) table, which references the primary key(USER-ID) of the users. The key fails to match the USER-ID.
Any advice would be really helpful. Thank you a lot in advance.
Posting some of the code below:
register.php
<?php include('server.php') ?>
<? php
if (isset($_SESSION['username'])) {
$_SESSION['msg'] = "You're now logged in.";
unset($_SESSION["register.php"];
header('Location: user_index.php');
}
?>
<!DOCTYPE html>
<html>
<link href="https://fonts.googleapis.com/css?family=Eater" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<body>
<p id="pagetitle">Booking Planet </p>
<div class="navbar" id="topnav">
<button onclick="document.getElementById('id01').style.display='block'"
style="width:auto;">Login</button>
<button onclick="document.getElementById('id02').style.display='block'"
style="width:auto;">Register</button>
HOME
</div>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT * FROM accom");
echo "<p> </p>";
echo "<div class='acclist'> Explore some fairytale destinations.. </div>";
echo "<ul>";
while($row = mysqli_fetch_array($result))
{
$image=$row['image'];
$target = "images/".basename($image);
echo "<img src='" . $target . "' width=800 height=500/>";
echo "<li id='title'><b>" . $row['title'] . "</b></li>";
echo "<li> Description: <i>" . $row['description'] . "</i></li>";
echo "<li> Address: <i>". $row['address'] . "</i></li>";
echo "<li> Available from: <i>" . $row['checkin'] . "</i></li>";
echo "<li> Available until: <i>" . $row['checkout'] . "</i></li>";
?><button onclick="document.getElementById('id01').style.display='block'"
type='button' class='bookbtn'>Log-in to book now!</button>
<?php
echo "<li><img src='sepline.png' width=1500 height=75> </li>";}
echo "</ul>";
mysqli_close($db);
?>
</div>
<div id="id01" class="modal">
<? php include('errors.php'); ?>
<form action="" method="post" class="modal-content animate" name="login" >
<div class="logocontainer"> Booking Planet
</div>
<h3> Account Log-in. </h3>
<div class="container">
<? php echo $errors; ?>
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password"
required>
<button type="submit" name="login_user">Login</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl1">Cancel</button>
</div>
</form>
</div>
<!-- REGISTRATION -->
<div id="id02" class="modal">
<form action="" method="post" class="modal-content animate" name="register"
>
<div class="logocontainer"> Booking Planet
</div>
<h3> Create an account. </h3>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Name</b></label>
<input type="text" placeholder="Enter your Name!" name="name" required>
<label><b>Surname</b></label>
<input type="text" placeholder="Enter your Surname!" name="surname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>Email</b></label>
<input type="email" placeholder="Enter Email" name="email" required>
<div class="avatar"><label>Select your avatar: </label>
<input type="file" name="avatar" accept="image/*" required />
<button type="submit" name="reg_user">Register</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl2">Cancel</button>
</div>
</form>
</div>
<script src="myscripts.js"></script>
</body>
</html>
user_index.php: is pretty much similar to register.php, it's where people who have registered or logged-in are redirected. I'm posting the beginning of the code.
<?php include('server.php'); ?>
<?phpinclude('auth.php');
session_start();
if ($_SESSION['username']<1) {
session_destroy();
unset($_SESSION['username']);
header("Location: register.php");
}
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT email FROM users WHERE
username='$_SESSION['username']'");
$row = mysqli_fetch_array($result);
$_SESSION['email'] = $result;
$username = $_SESSION['username'];
$_SESSION['id']=$id;
header("Location: server.php");
?>
server.php: contains the validation for registration and logging-in. Also, links to the DB. I will be skipping the validation parts.
<?php
session_start();
$email=$_SESSION['email'];
// initializing variables
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
//...validationon code
//once no errors, register user
if (count($errors) == 0) {
$password = md5($password);//encrypt the password before saving in the
database
$query = "INSERT INTO users (username, email, password, name, surname)
VALUES('$username', '$email', '$password', '$name', '$surname')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}
}
// LOGIN USER
$msg = '';
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_start();
$_SESSION['email']=$row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['id']= $id;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}else {
echo $msg;
}
}
}
auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
echo $errors; }
?>
For any additional information you might need, please feel free to ask anything.
I am genuinely sorry for the block of text and code.
Related
I'm a beginner and need some help with my code.
If I enter the webpage index.php, I want to be redirected to login.php if I'm not logged in.
I'm using this code and it works so I redirects to login.php, but I can't log in. I'm stuck at login.php.
I have this code in my index.php
<?php
if(isset($_SESSION['userId'])) {
// comment
} else {
header("Location:login.php");
}
?>
Parts of my login.php
<?php
include('template.php');
if (isset($_POST['username']) and isset($_POST['password'])) {
$name = $mysqli->real_escape_string($_POST['username']);
$pwd = $mysqli->real_escape_string($_POST['password']);
$query = <<<END
SELECT username, password, user_id FROM users4project
WHERE username = '{$name}'
AND password = '{$pwd}'
END;
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_object();
$_SESSION["username"] = $row->username;
$_SESSION["user_id"] = $row->user_id;
header("Location:index.php");
} else {
echo "Wrong username or password. Try again";
}
}
$content = <<<END
<form action="login.php" method="post">
<div class="form-group">
<input type="text" class="form-control form-control-user" name="username" required placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" name="password" required placeholder="Password">
</div>
<div class="form-group">
<div class="custom-control custom-checkbox small">
<input type="checkbox" class="custom-control-input" id="customCheck">
<label class="custom-control-label" for="customCheck">Remember Me</label>
</div>
</div>
<input type="submit" value="Login" class="btn btn-primary btn-user btn-block">
</form>
END;
echo $navigation;
echo $content;
?>
my template.php
session_name('Website');
session_start();
$host = "localhost";
$user = " ";
$pwd = " ";
$db = " ";
$mysqli = new mysqli($host, $user, $pwd, $db);
isset($_SESSION['userId'] !== $_SESSION["user_id"]
aside from the major security issues, you're not comparing the right session name
(for clarity)
You check
<?php
if(isset($_SESSION['userId'])) {
// comment
but you set
if ($result->num_rows > 0) {
....
$_SESSION["user_id"] = $row->user_id;
.....
PappaJ says "pick a naming convention, and stick with it"
I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}
I've created a login/registration system and the registration part is working fine. However, now I am trying to login and when you login it should start a session and redirect you to account.php page but it's not doing that. It's just refreshing the page and doing nothing else.
Index page:
<?php
include 'dbh.php';
session_start();
if(isset($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".$_SESSION['id']);
$row = $result->fetch_array(MYSQLI_BOTH);
}
# REGISTRATION HANDLER
if(isset($_POST['rsubmit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$plainpass = $_POST['password'];
$password = password_hash($plainpass, PASSWORD_BCRYPT, array('cost' => 10));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($conn, $sql);
$btn = "Account created! Please login";
}else {
$btn = "Register";
}
# LOGIN HANDLER
if(isset($_POST['lsubmit'])){
$lemail = $_POST['lemail'];
$lpassword = $_POST['lpassword'];
$result = $conn->query("SELECT * FROM users where email='$lemail'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($lpassword, $row['password'])){
$_SESSION['id'] = $row['id'];
Header("Location: account.php");
}
} else {
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
DBH.php:
<?php
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(isset($_SESSION['id'])){
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
}
?>
Instead of Header("Location: account.php");
use the following statement
echo "<script>location.href='account.php'</script>";exit;
The issue as mentioned by Jeff, it can be due to space the redirection is not happening. If the above logic works. Then remove additional space in config / else need to add session_start() as the first line of statement in your index.php file and have the header("Location: account.php") logic.
Note: To debug, ensure the control goes here by printing and adding a exit statement.
try
Index page:
<?php
session_start();
include 'dbh.php';
-----code---------
?>
DBH.php:
<?php
session_start();
-----code---------
?>
//session_start(); needed to give top of page and here it is missing in DBH.php. Hence $_SESSION not working
Try next approach:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(!empty($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".(int)$_SESSION['id']);
if(!$result->num_rows) {
session_destroy();
Header("Refresh:0");
exit;
}
Header("Location: account.php");
exit;
}
# LOGIN HANDLER
if(isset($_POST['lsubmit']) && !empty($_POST['lemail'])){
$lemail = mysqli_real_escape_string($_POST['lemail']);
$result = $conn->query("SELECT * FROM users where email='{$lemail}'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($_POST['lpassword'], $row['password'])){
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
Header("Location: account.php");
exit;
}
}
# REGISTRATION HANDLER
elseif(isset($_POST['rsubmit']) && !empty($_POST['email'])){
$username = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT, array('cost' => 10));
$result = $conn->query("INSERT INTO users (username, email, password) VALUES ('{$username}', '{$email}', '{$password}')");
$btn = "Account created! Please login";
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
I was trying to create a login page, but it doesn't seem to work. When I enter details and click login. Nothing happens. I try to login again, still nothing happens. I want to happen is when i login a popup window will appear and i will be directed to the homepage
<?php
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class = "boxlog1"
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
}
else{
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
Add the page to the form action
For example:
<form action"login.php">
Or use
<form action"<?php echo $_SERVER['PHP_SELF']; ?>">
And close your div tag with '>', so
<div class="boxlog1">
Working example
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
And here with updated security against SQL Injection. Dont forget to encrypt your password so it cannot be stolen
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log']) && isset($_POST['uname']) && isset($_POST['lpass'])){
$c_email = bin2hex(htmlspecialchars($_POST['uname']));
$c_pass = bin2hex(htmlspecialchars($_POST['lpass']));
$sel_c = "SELECT * FROM customers WHERE customer_pass=UNHEX('$c_pass') AND customer_email=UNHEX('$c_email')";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer === 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
I did'nt changed really much. Just closed your div tag correctly and added an action. However, it does work without the action filled in.
index.php :
<?php
session_start();
require 'res/connection.php';
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to the members section, Login or Register</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="js/fadein.js"></script>
<link rel="stylesheet" type="tex/css" href="css/master.css"/>
<link rel="stylesheet" type="tex/css" href="css/form.css"/>
</head>
<body>
<div class="container loginbdy">
<div class="row">
<div class="col-lg-12 loginform">
<form action="" method="post" class="form">
<h2>Log In :</h2>
<label name="username-label">Username :</label>
<input class="form-control" type="text" placeholder="Your username" name="username" id="username" maxlength="120"/>
<label name="password-label">Password :</label>
<input class="form-control" type="password" placeholder="Your password" name="password" id="password" maxlength="35"/></br>
<input type="submit" class="btn btn-default" value="Log In" name="submit" /></br>
<p>Not a member yet ? <a href="register.php" ><i><b>register</b></i></a></p>
</form>
</div>
<div class="col-lg-3 errorlogin">
<?php
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
if(empty($username)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> username is empty.
</div>
';
}elseif(empty($password)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> password is empty.
</div>
';
}else{
$result = mysqli_query($con,"SELECT * FROM `users` WHERE `username` = '$username'");
$row_cnt = mysqli_num_rows($result);
if($row_cnt === 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The username you tried to login with doesn\'t exist, would you like to register it ?
</div>
';
}else{
$row = mysqli_fetch_array($result);
$userpassword = $row['password'];
$salt = $row['salt'];
$id = $row['user_id'];
$hashedpassword = crypt($password,$salt);
if($hashedpassword === $userpassword){
$_SESSION['id'] = $id;
echo "
<div class=\"alert alert-success\">
<strong>Session has been set</strong> you are now logged in! your user id is "; echo $_SESSION['id']; echo '
</div>
';
$user_id = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username'");
$row = mysqli_fetch_array($user_id);
$id = $row['user_id'];
$firstname = $row['first name'];
$lastname = $row['last name'];
$semail = $row['email'];
$susername = $row['username'];
$spaid = $row['paid'];
$sdate = $row['date_created'];
$sconfirmed = $row['confirmed'];
$_SESSION['id'] = $id;
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $semail;
$_SESSION['username'] = $susername;
$_SESSION['paid'] = $spaid;
$_SESSION['date'] = $sdate;
$_SESSION['confirmed'] = $sconfirmed;
header('Location: profile.php');
}else{
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The username or password you entered is incorrect!
</div>
';
}
}
}
}
?>
</div>
</div>
</div>
</body>
</html>
register.php :
<?php
session_start();
require 'res/connection.php';
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to the members section, Login or Register</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="tex/css" href="css/master.css"/>
<link rel="stylesheet" type="tex/css" href="css/form.css"/>
</head>
<body background="res/background.jpg">
<div class="container">
<div class="row">
<div class="col-lg-9 registerform">
<?php
?>
<form action="" method="post" class="form">
<h2>Register :</h2>
<label name="lname-label">First Name :</label>
<input class="form-control" type="text" placeholder="Your First Name" name="fname" id="fname" maxlength="100" tabindex="1" autofocus />
<label name="lname-label">Last Name :</label>
<input class="form-control" type="text" placeholder="Your Last Name" name="lname" id="lname" maxlength="100" tabindex="2" />
<label name="username-label">Username :</label>
<input class="form-control" type="text" placeholder="Your desired Username" name="username" id="username" maxlength="24" tabindex="3" />
<label name="email-label">Email :</label>
<input class="form-control" type="email" placeholder="Your Email address" name="email" id="email" maxlength="120" tabindex="4" />
<label name="password-label">Password :</label>
<input class="form-control" type="password" placeholder="Your desired password" name="password" id="password" maxlength="35" tabindex="5" />
<label name="repassword-label">re enter Password :</label>
<input class="form-control" type="password" placeholder="Your password again" name="repassword" id="repassword" maxlength="35" tabindex="6" />
<label name="type-label">i am here to :</label></br>
<select name="type" class="form-control" tabindex="7" >
<option>develop websites</option>
<option>hire a developer</option>
</select>
</br>
<input type="submit" class="btn btn-default" value="Register" name="submit" /></br>
<p>already a member ? <a href="index.php" ><i><b>Log In</b></i></a></p>
</form>
</div>
<div class="col-lg-3 errorlog">
<?php
/* if submit button is clicked start the registration */
if(isset($_POST['submit'])){
/* get all the values from the textboxes */
$fname = mysqli_real_escape_string($con,$_POST['fname']);
$lname = mysqli_real_escape_string($con,$_POST['lname']);
$username = mysqli_real_escape_string($con,$_POST['username']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$password_verification = mysqli_real_escape_string($con,$_POST['repassword']);
$type = mysqli_real_escape_string($con,$_POST['type']);
$paid = false;
/* form validation */
if(empty($fname)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> first name is empty.
</div>
';
}else if(empty($lname)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Last name is empty.
</div>
';
}else if(empty($username)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Username is empty.
</div>
';
}else if(0 === preg_match("/.+#.+\..+/",$email)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The email you entered is invalid.
</div>
';
}else if(0 === preg_match("/.{6,}/",$password)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Passwords has to be atleast 6 characters long.
</div>
';
}else if($password !== $password_verification){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The passwords you entered do not match.
</div>
';
}else if(empty($type)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> You can be eithere a developer or a host
</div>
';
}else{
$query = "SELECT * FROM users WHERE username = '$username'";
$equery = "SELECT * FROM users WHERE email = '$email'";
if($result = mysqli_query($con,$query)){
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> This username is already taken!
</div>
';
}else if ($eresult = mysqli_query($con,$equery)){
$erow_cnt = mysqli_num_rows($eresult);
if($erow_cnt > 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> This email is already registered!
</div>
';
}else{
$salt = rand(100 , 999) . rand(100 , 999) . rand(1000 , 9999);
$hashedpassword = crypt($password,$salt);
if($type === "develop websites"){
$type="developer";
}else if($type === "hire a developer"){
$type="owner";
}else{
echo'
<div class="alert alert-danger">
<strong>Error!</strong> you can only be an owner or a developer
</div>
';
}
$date = date("m/d/Y h:i:sa");
$confirm = false;
$confirmation_code = rand(100,999) . "-" . rand(100,999);
$insertion = mysqli_query($con,"INSERT INTO `users` (`first name`, `last name`, `email`, `password`, `username`, `salt`, `type`, `paid`, `date_created`, `confirmed`,`confirmation_code`) VALUES ('$fname','$lname','$email','$hashedpassword','$username','$salt','$type','0','$date','$confirm','$confirmation_code')");
if($insertion){
echo "
<div class=\"alert alert-success\">
<strong>Success</strong> your account has been successfully created!
</div>
";
$user_id = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username'");
$row = mysqli_fetch_array($user_id);
$id = $row['user_id'];
$firstname = $row['first name'];
$lastname = $row['last name'];
$semail = $row['email'];
$susername = $row['username'];
$spaid = $row['paid'];
$sdate = $row['date_created'];
$sconfirmed = $row['confirmed'];
$sconfirmation_code = $row['confirmation_code'];
$_SESSION['id'] = $id;
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $semail;
$_SESSION['username'] = $susername;
$_SESSION['paid'] = $spaid;
$_SESSION['date'] = $sdate;
$_SESSION['confirmed'] = $sconfirmed;
$_SESSION['confirmation_code'] = $sconfirmation_code;
if($user_id){
echo "
<div class=\"alert alert-success\">
<strong>Session has been set</strong> you are now logged in!
</div>
";
echo"<script>
setTimeout(function () {
window.location.href = 'profile.php';},8000);
</script>";
echo "
<div class=\"alert alert-info\">
<strong>Thank you!</strong> in 8 seconds you will be redirected to your new profile
</div>
";
}else{
echo "
<div class=\"alert alert-danger\">
<strong>Failed</strong> your account has been created, but we were unable to log you in, you will have to do this manually here
</div>";
}
}else{
echo "
<div class=\"alert alert-danger\">
<strong>Failed</strong> your account has not been created, something went wrong
</div>";
}
}
}
}
}
}
?>
</div>
</div>
</div>
</body>
</html>
now the thing is that once u go to login or register it checks if you have a session ongoing by checking this :
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
but it is returning an error saying :
Notice: Undefined index: id
i understand that the error is because the session is not set so the variable $_SESSION['id'] is not set which is causing this error, what i would like to know is if there is another way around this that does not include the use of cookies, because i am storing user info, and cookies are not safe in that case
i tried using session_id(), but whenever you start a session the session_id() is automatically set. so it will always redirect to profile.php even if your not logged in
ps : i know my php is not very neat and tidy, i am still new at php, so any comments about improving it will be much appreciated
Try isset :-
if(isset($_SESSION['id'])){
header("Location: profile.php");
}else{
echo 'session is not set';die;
}
Use isset!
if (isset($_SESSION['id'])) {
// ..
}
Isset checks if the var/index is defined, so this would work perfectly for you.
Keep in mind, there's an difference between isset and !empty. isset only checks, if the var is defined, !empty does some more test, like $var !== false, $var !== array(), $var !== '0', $var !== 0, etc..
This probably doesn't matter in your case(except, you have an allowed id=0), but is always good to know.
<?php
Session_start();
if(isset($_SESSION['id'])
Do what you wanna do
?>
You can use isset() to see if id is set or no.
if(isset($_SESSION['id'])){
header("location: profile.php");
}
In php isset() is used to check that id is set or not.