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.
Related
Hello good afternoon, I'm having the trouble of not being able to use add a $_POST value to my $_SESSION variable so that I can use it later in my profile file.
I can give it other values like "hello" outside the if and it echoes hello in levraiprofilewesh.php.
I've tried making $_SESSION a super global variable and global but it didn't work.
I've been stuck on it for a few hours :(.
I don't need to upload the website on the web, it's just for local use, so there's no need for privacy feedback although it has helped me for the future.
login.php code:
<?php
session_start();
include("db_connect.php");
if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$_SESSION['password'] = $user_password;
$usql = "SELECT * FROM users WHERE Email='$user_email' && Password='$user_password'";
$uresult = mysqli_query($db, $usql) or die("database error:". mysqli_error($db));
$urow = mysqli_fetch_assoc($uresult);
//while($row = mysqli_fetch_array($uresult))
//$STPMARCHEFRERE = $row['Firstname'];
//$SESSION = $row['Firstname'];
if($urow['Password']==$user_password){
setcookie("userid",$user_password,time()+(60*60*24*7));
setcookie("useremail",$user_email,time()+(60*60*24*7));
//$GLOBALS['SESSION'] = $user_password;
$time=time();
$queryz = "UPDATE Users
Set Online='Online',
Time='$time'
WHERE Password='$user_password' ";
$db->query($queryz) or die('Errorr, query failed to upload');
echo "ok";
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
levraiprofilewesh.php code:
<?php
session_start();
include("login.php");
$connection = mysqli_connect('localhost', 'root','','phpchart');
if(isset($_SESSION['password'])) {
$username = $_SESSION['password'];
$query = "SELECT *
FROM users
WHERE Password = '%$username%'";
$select_user_profile_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($select_user_profile_query)) {
$post_tamere = $row['Firstname'];
$post_tondaron = $row['Sirname'];
$post_tasoeur = $row['Phone'];
$post_tonneveu = $row['Institution'];
$post_julia = $row['Email'];
}
}
?>
<?php
if(isset($_POST['edit_user'])) {
$user_firstname = $_POST['user_firstname'];
$user_lastname = $_POST['user_lastname'];
$user_role = $_POST['user_role'];
//$post_image = $_FILES['image']['name'];
//$post_image_temp = $_FILES['image']['tmp_name'];
$username = $_POST['username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
//$post_date = date('d-m-y');
//move_uploaded_file($post_image_temp, "./images/$post_image" );
$query = "SELECT randSalt FROM users";
$select_randsalt_query = mysqli_query($connection, $query);
if(!$select_randsalt_query) {
die("Query Failed" . mysqli_error($connection));
}
$row = mysqli_fetch_array($select_randsalt_query);
$salt = $row['randSalt'];
$hashed_password = crypt($user_password, $salt);
$query = "UPDATE users SET ";
$query .="user_firstname = '{$user_firstname}', ";
$query .="user_lastname = '{$user_lastname}', ";
$query .="user_role = '{$user_role}', ";
$query .="username = '{$username}', ";
$query .="user_email = '{$user_email}', ";
$query .="user_password = '{$hashed_password}' ";
$query .= "WHERE username = '{$username}' ";
$edit_user_query = mysqli_query($connection,$query);
confirmQuery($edit_user_query);
}
?>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<div id="wrapper">
<!-- Navigation -->
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Welcome to Profile
<small>Author</small>
</h1>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Firstname</label>
<input type="text" value="<?php echo $post_tamere; ?>" class="form-control" name="user_firstname">
</div>
<div class="form-group">
<label for="post_status">Lastname</label>
<input type="text" value="<?php echo $post_tondaron; ?>" class="form-control" name="user_lastname">
</div>
<div class="form-group">
<select name="user_role" id="">
<option value="subscriber"><?php echo $user_role; ?></option>
<?php
if($user_role == 'admin') {
echo "<option value='subscriber'>subscriber</option>";
} else {
echo "<option value='admin'>admin</option>";
}
?>
</select>
</div>
<!--<div class="form-group">
<label for="post_image">Post Image</label>
<input type="file" name="image">
</div>-->
<div class="form-group">
<label for="post_tags">Phone</label>
<input type="text" value="<?php echo $post_tasoeur; ?>" class="form-control" name="username">
</div>
<div class="form-group">
<label for="post_content">Email</label>
<input type="email" value="<?php echo $post_tonneveu; ?>" class="form-control" name="user_email">
</div>
<div class="form-group">
<label for="post_content">Password</label>
<input type="password" value="<?php echo $post_julia; ?>" class="form-control" name="user_password">
</div>
<h1><?php echo $_SESSION['superhero']; ?></h1>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="edit_user" value="Update Profile">
</div>
</form>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
I have a register page for users who can register using email, with email activation and Google captcha. My register code is as follows:
<?php
require_once('connect.php');
include('config.php');
include('recaptchalib.php');
$response = null;
$reCaptcha = new ReCaptcha($secret);
if(isset($_POST) & !empty($_POST)){
if($_POST['g-recaptcha-response']){
$response = $reCaptcha->verifyResponse(
$_SERVER['REMOTE_ADDR'],
$_POST['g-recaptcha-response']
);
}
if($response != null && $response->success){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$verification_key = md5($username);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = md5($_POST['password']);
$passwordagain = md5($_POST['passwordagain']);
if($password == $passwordagain){
$fmsg = "";
$usernamesql = "SELECT * FROM `usermanagement` WHERE username='$username'";
$usernameres = mysqli_query($connection, $usernamesql);
$count = mysqli_num_rows($usernameres);
if($count == 1){
$fmsg .= "Username exists in Database, please try different user name";
}
$emailsql = "SELECT * FROM `usermanagement` WHERE email='$email'";
$emailres = mysqli_query($connection, $emailsql);
$emailcount = mysqli_num_rows($emailres);
if($emailcount == 1){
$fmsg .= "Email exists in Database, please reset your password";
}
echo $sql = "INSERT INTO `usermanagement` (username, email, password, verification_key) VALUES ('$username', '$email', '$password', '$verification_key')";
$result = mysqli_query($connection, $sql);
if($result){
$smsg = "User Registered succesfully";
$id = mysqli_insert_id($connection);
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = $smtphost;
$mail->SMTPAuth = true;
$mail->Username = $smtpuser;
$mail->Password = $smtppass;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('admin#teia.website', 'BookTheParty');
$mail->addAddress('zubairoliyatofficial#gmail.com', 'Zubair Nazer');
$mail->Subject = 'Verify Your Email';
$mail->Body = "http://localhost/user-management/verify.php?key=$verification_key&id=$id";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}else{
$fmsg .= "Failed to register user";
}
}else{
$fmsg = "Password not matching";
}
}
}
?>
<html>
<head>
<title>User Registration Script in PHP & MySQL</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<link rel="stylesheet" href="styles.css" >
<script src="https://code.jquery.com/jquery-3.1.1.js" ></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#usernameLoading').hide();
$('#username').keyup(function(){
$('#usernameLoading').show();
$.post("check.php", {
username: $('#username').val()
}, function(response){
$('#usernameResult').fadeOut();
setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#usernameLoading').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
} //finishAjax
</script>
</head>
<body>
<div class="container">
<?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 } ?>
<form class="form-signin" method="POST">
<h2 class="form-signin-heading">Please Register</h2>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">#</span>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" value="<?php if(isset($username) & !empty($username)){ echo $username; } ?>" required>
<span id="usernameLoading" class="input-group-addon"><img src="loading.gif" height="30px" alt="Ajax Indicator" /></span>
</div>
<span id="usernameResult"></span>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" value="<?php if(isset($email) & !empty($username)){ echo $email; } ?>" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword" class="sr-only">Password Again</label>
<input type="password" name="passwordagain" id="inputPassword" class="form-control" placeholder="Password Again" required>
<div class="g-recaptcha" data-sitekey="6LeQ3K0UAAAAAM4QHKFXmNL_6xrCqa6qlSS1NdXi"></div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
<a class="btn btn-lg btn-primary btn-block" href="login.php">Login</a>
</form>
</div>
<?php require_once('credits.php'); ?>
</body>
</html>
Now when the user tries to register, no error is showing and the values are not added to the database. Also, it's simply reloading the page. Can anyone please tell me whats wrong with my code?
The only thing that I've managed to spot is that you're trying to define a variable within an echo, when you do the insert. Try having '$sql' just by itself like below... hope this helps :)
<?php
$sql = "INSERT INTO `usermanagement` (username, email, password, verification_key) VALUES ('$username', '$email', '$password', '$verification_key')";
$result = mysqli_query($connection, $sql);
?>
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.
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I am trying to make a simple register page where users register with username, email, password and gender. I somehow stumbled over some problems, the code I made seems to let users register with a username or e-mail that already exists. I tried to prevent this in my code but it doesn't seem like it worked.
What am I doing wrong?
Here is the whole code:
<?php
session_start();
if (isset($_SESSION['user'])!="") {
header("Location: index.php");
}
include 'includes/config.php';
if(isset($_POST['btn-signup'])) {
$username = strip_tags($_POST['username']);
$username = strtolower($_POST['username']);
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
$email = filter_var($email,FILTER_VALIDATE_EMAIL);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$current_time = strtotime("now");
$username = $con->real_escape_string($username);
$gender = $con->real_escape_string($_POST["gender"]);
$email = $con->real_escape_string($email);
$password = $con->real_escape_string($password);
$hashed_password = password_hash($password, PASSWORD_DEFAULT); // this function works only in PHP 5.5 or latest version
$check_username = $con->query("SELECT * FROM users WHERE username='$username' LIMIT 1");
$check_email = $con->query("SELECT * FROM users WHERE email='$email' LIMIT 1");
if(count($_POST)>0) {
if(!isset($msg)) {
}
if($_POST['username'] === $check_username){
$msg = 'Username already exists<br>';
}
if($_POST['email'] === $check_email){
$msg = 'Email already exists<br>';
}
if($_POST['password'] != $_POST['confirm_password']){
$msg = 'Password doesnt match<br>';
}
if(!isset($msg)) {
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$msg = "Invalid e-mail";
}
}
if(!isset($msg)) {
if(!isset($_POST["gender"])) {
$msg = " Gender field is required";
}
}
}
if(!isset($msg)) {
$query = "INSERT INTO users(username,email,password,gender,joined) VALUES('$username','$email','$hashed_password','$gender','$current_time')";
if(mysqli_query($con, $query)){
$msg = "You have registered successfully!";
} else{
$msg = "Could not register your account. Try Again!";
}
}
}
$con->close();
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Register</title>
</head>
<body>
<div class="signin-form">
<div class="container">
<form class="form-signin" id="register-form" method="post" name="register-form">
<h2 class="form-signin-heading">Sign Up</h2>
<hr>
<?php
if (isset($msg)) {
echo $msg;
}
?>
<div class="form-group">
<input class="form-control" name="username" placeholder="Username" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" name="email" placeholder="Email address" required="" type="email"> <span id="check-e"></span>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" required="" type="password">
</div>
<div class="form-group">
<input class="form-control" name="confirm_password" placeholder="Confirm password" required="" type="password">
</div>
<div class="form-group">
<select class="form-control" id="gender" name="gender">
<option disabled hidden="" selected>
Select
</option>
<option>
Male
</option>
<option>
Female
</option>
</select>
</div>
<hr>
<div class="form-group">
<button class="btn btn-default" name="btn-signup" type="submit"><span class="glyphicon glyphicon-log-in"></span> Create Account</button> <a class="btn btn-default" href="index.php" style="float:right;">Log In Here</a>
</div>
</form>
</div>
</div>
</body>
</html>
The problem is that you do not fetch your result from the sql result.
So $con->query($sqlQuery); will return a PDOStatement object. You can't compare a such object with a string. So first you need to extract the string. This will work like this:
$check_username_result = $con->query("SELECT * FROM users WHERE username='$username' LIMIT 1")
$check_username = $check_username_result->fetch_array()[0];
$check_username will now hold the value of the username and you can compare it as you do.
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;
}