Show DIV in other .php file only when php statement is true - php

quick question. I'm a rookie so,
when registration success I want to show <div> with a message(value).
So if everything is alright only then should appear on another .php file with HTML code.
I tried to return it but cannot figure out how to do it in the right way.
NOTE:
Now I'm using global but I want to throw it out.
So I have a function in function.php and if...
function createUser(){
global $welcome;
$connection = connectDB();
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST["passwordConfirm"];
$username = mysqli_real_escape_string($connection, $username);
$email = mysqli_real_escape_string($connection, $email);
$password = mysqli_real_escape_string($connection, $password);
$passwordConfirm = mysqli_real_escape_string($connection, $passwordConfirm);
if($_POST['password'] !== $_POST['passwordConfirm']){
$error = exit("Password does not match.");
}
$hashFormat = "$2y$10$";
$salt = "iusesomecrazystrings22";
$hash = $hashFormat . $salt;
$password = crypt($password, $hash);
$query = "INSERT INTO users(username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $query);
if(!$result){
die("Query FAILED " . mysqli_error($connection));
} else{
$welcome = "Registration Success";
}
}
And in other file I have something like this:
<?php
include 'functions.php';
global $welcome;
if(isset($_POST['submit'])){
createUser();
}
?>
<div class="row justify-content-md-center">
<form action="register.php" method="post">
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username" style="text-align: center" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" style="text-align: center" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" style="text-align: center" required>
</div>
<div class="form-group">
<input type="password" name="passwordConfirm" class="form-control" placeholder="Confirm Password" style="text-align: center" required>
</div>
<div class="row justify-content-md-center">
<input type="submit" name="submit" value="SIGN UP" class="btn btn-primary">
</div>
<p></p>
<div class="row justify-content-md-center">
<?php echo $welcome; ?>
</div>
</form>
</div>
So I did it this way...
How should I return instead of $welcome = "Registration Success";, show it ONLY if $result is true and finally print that message in other file that contains HTML.

You can return $message from the function and receive it like this:
if(isset($_POST['submit'])){
$message = createUser();
}
and modify your function createUser like this:
UPDATED
function createUser()
{
// here is your function's body))))
if ($result) {
return "Registration Success";
}
die("Query FAILED " . mysqli_error($connection));
}

if I understand properly:
In createUser(), instead of:
if(!$result){
die("Query FAILED " . mysqli_error($connection));
} else{
$welcome = "Registration Success";
}
Do this:
if(!$result){
die("Query FAILED " . mysqli_error($connection));
}
return true;
And in the PHP file with the HTML do this:
<?php
include 'functions.php';
$userCreated = false;
if(isset($_POST['submit'])){
$userCreated = createUser();
}
if ($userCreated) { ?>
Here goes your message about successfull user creation, or you can use echo '' and you can skip PHP open close tag
<?php } else { ?>
<div class="row justify-content-md-center">
<form action="register.php" method="post">
...
</form>
</div>
<?php }
?>
With this you dont need to use global, instead you use createUser function's return value, which tells you wheter it was successfull or not.

Related

Redirect to login.php if not logged in

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"

Unable to retrieve data from DB and using $_SESSION variable

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.

Login php script unable to call infromation from db

Good day.
So below i have a php script that is supposed to query my db and look for user details. the db is set up and the data is available in it. the issue here seems that once i click the submit button with my user entered details, it fails on the first if statement, to see if the email exists. i am not sure why.
But here is the submit form.
<form action = "submit2.php" method="Post" >
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" name="email" class="form-control" placeholder="Your user name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="text" id="password" name="password" class="form-control" placeholder="Your Password">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary">
</div></form>
and here is the submit2.php that is supposed to manipulate the data from the form and query the db.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$useremail = mysqli_real_escape_string($connection,$_POST['email']);
$userpassword = mysqli_real_escape_string($connection, $_POST['password']);
if (empty($useremail) || empty($userpassword)){
header("Location: customerportal.php?login=empty");
exit();
}
else{
$sql = "SELECT * FROM 'USERS' where EMAIL ='$useremail';";
$emailresult = mysqli_query($connection, $sql);
$emailresultcheck = mysqli_num_rows($emailresult);
//check if email exists
if($emailresultcheck == 0){
header("Location: customerportal.php?login=invalidEmail");
}
else {
if($row = mysqli_fetch_assoc($emailresult)){
//dehash the password
$hashedPWDCheck = password_verify($userpassword,$row['ENCRYPTEDPWD']);
if($hashedPWDCheck == false){
header("Location: customerportal.php?login=passwordincorrect");
exit();
}
elseif($hashedPWDCheck == true){
$_SESSION['email'] = $email;
// header("Location: Landingpage.php");
echo "Success";
}
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
}
}
?>
The submit always fails else statement and returns the invalidEmail header location and i am not sure why. the Connection file is below.what am i missing?
<?php
$connection = mysqli_connect("localhost", "root", "");
if(!$connection){
echo "Failed to connect database" . die(mysqli_error($connection));;
}
$dbselect = mysqli_select_db($connection, "dhctest");
if(!$dbselect){
echo "Failed to Select database" . die(mysqli_error($connection));
}
?>
Change this
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
to this
$sql = "select * from users where email = $useremail";
Okay, so solved the issue, by running a var_dump() on everyone of my variables until i came across the error that was being outputted by my sql code.
On the line
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
I had to remove the '' and replace with ``.
And that seems to have solved the issue.
Thank you for everyone who assisted.

How can I echo the "Username/Email should not be empty!" in the fields?

Ok, right now when the user does not fill in the fields correctly he is redirected to this What I want is to make it more user-friendly and so the user can see their mistake in the fields or at least in the same page without being redirected to this white page.
Here is my code so far:
Conn.php
<?php
session_start();
$username = $_POST['username'];
$password =$_POST['password'];
$email = $_POST ['email'];
$phone = $_POST['phone'];
if(!empty ($username) && !empty($email)){
if(!empty ($password)){
$host = "host";
$dbusername = "user";
$dbpassword = "********";
$dbname = "dbname";
$conn = new mysqli ($host,$dbusername,$dbpassword,$dbname);
if(mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno().')' . mysqli_connect_error());
}
else{
$username= mysqli_real_escape_string($conn,$_POST["username"]);
$email= mysqli_real_escape_string($conn,$_POST["email"]);
$phone= mysqli_real_escape_string($conn,$_POST["phone"]);
$password= mysqli_real_escape_string($conn,$_POST["password"]);
$password = password_hash($password,PASSWORD_DEFAULT);
$sql = "INSERT INTO user(username,password,email,phone) values('$username','$password','$email','$phone')";
if($conn->query($sql)){
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
else{
echo "error: ". $sql."<br>".$conn->error;
}
$conn->close();
}
}
else {
echo "Password should not be empty";
//echo "<script>alert('Password should not be empty!');</script>";
die();
}
}
else{
echo "Username/Email should not be empty";
die();
}
?>
SignUp.php
<?php
include_once 'header.php';
?>
<h1 class="register"> Rigester </h1>
<div class="help" >
<form method="POST" action="conn.php">
<div class="help">
<input placeholder="Username" type="text" name="username" >
</div>
<div class="help">
<input placeholder="Password" type="password" name="password" >
</div>
<div class="help">
<input placeholder="Email" type="text" name="email" >
</div>
<div class="help">
<input placeholder="Phone" type="text" name="phone" >
</div>
<input class="helpbtn" type="submit" name="submit" >
</form>
</div>
<?php
include_once 'footer.php';
?>
you can use it like this
in conn.php:
// form error
if(condiftion){
header("location:www.example.com/SignUp.php?msg=1");
}
in signup.php
//you can print diffrent message By judging value of $_GET[''msg'] with switch
<?php echo isset($_GET["msg"]) "your message" : "";?>

Failing connecting/submitting to MySQL with "PHP form"

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;
}

Categories