Someone can check my session? - php

Please someone can check whether my session is working or not.
I am not sure as i am still beginner.
login.php is the main page for user to login the username and password :
<body>
<form action="" method="post">
<div class="imgcontainer">
<img src="KBR2xN6.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<br />
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required>
<button type="submit">Login</button>
<button type="reset" class="cancelbtn">Reset</button>
</div>
</form>
</body>
As for connections.php is to connect to the local server :
$host = "localhost";
$username = "root";
$password = "";
$database = "netbook 1 malaysia";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'Connection Failed : '.$ex->getMessage();
}
As for session.php i am not sure:
session_start();
include('connections.php');
$username = $_POST['name'];
$password = $_POST['pass'];
$sql = "SELECT * FROM pengguna WHERE username = '$username' AND password = '$password'";
$result = $connect->query($sql);
if($result->rowcount()>0){
foreach($result AS $data){
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
echo "<script>alert('Login Success');
window.location.href='view.php';
</script>";
}
}
else {
echo "<script>alert('Login Failed');
window.location.href='login.php';
</script>";
}
Check for me please.

Just add this code to your view.php file.
session_start();
print_r($_SESSION);
If it prints values you saved in session then its working.

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"

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" : "";?>

Why do i got this : Array ( [name] => [pass] => )

Why do i get this when i print my session :
Array ( [name] => [pass] => ) ?
Below is my code
My main page for user to input, login.php:
<form action="" method="post">
<div class="imgcontainer">
<img src="KBR2xN6.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<br />
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required>
<button type="submit">Login</button>
<button type="reset" class="cancelbtn">Reset</button>
</div>
</form>
To connect to local server, connections.php:
$host = "localhost";
$username = "root";
$password = "";
$database = "netbook 1 malaysia";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'Connection Failed : '.$ex->getMessage();
}
My session page, session.php:
session_start();
include('connections.php');
$username = $_POST['name'];
$password = $_POST['pass'];
$sql = "SELECT * FROM pengguna WHERE username = '$username' AND password = '$password'";
$result = $connect->query($sql);
if($result->rowcount()>0){
foreach($result AS $data){
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
echo "<script>alert('Login Success');
window.location.href='view.php';
</script>";
}
}
else {
echo "<script>alert('Login Failed');
window.location.href='login.php';
</script>";
}
Maybe my database failed ?
$result contains a resource, not database data directly.
When we expected just one row form database, no loop is needed. Using a loop you'll have just on name/pass in session, it'll be overwritten in your code for the last one.
$data = $result->fetch_assoc();
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
print_r($_SESSION);
Note that there is no reason to store password in session, the same as store password in database as a plaintext.
Where you print session array? if you print session on view.php file then make sure to start session on view.php file.

Returning validation invalid login warning php script

I have already created a successfull login form that is connected to a database to determine whether or not a login is correct. But i would like to update this so that if an incorrect username or password is entered they will get an error message. Im just not to sure how to implement that into my existing code?...
my user login page:
<form action="../login.php" method="post">
<label for="login-username"><i class="icon-user"></i> <b>Username</b> </label><br/>
<input class="form-control" type="text" name="username">
<br/>
<label for="login-password"><i class="icon-lock"></i> <b>Password</b> </label> <br/>
<input class="form-control" type="password" name="password">
<br/>
<button type="submit" class="btn pull-right">Login</button>
</form>
<?php
if (isset($_SESSION['username'])){
if($_SESSION['logged_in'] = 1){
echo ('Logged in as: '. $_SESSION['username'].' '.$_SESSION['surname']).'<br>Log out';
}
}
?>
and the login.php it is posting to:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gpdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//echo "connection successful";
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM patients where Username ='$username' and Password ='$password'";
$result = $conn->query($sql);
$admin_user = 'admin';
$admin_password = 'admin1';
if ($result->num_rows > 0) {
if ($username === $admin_user || $password === $admin_password ){
foreach($result as $row) {
//echo "PatientID " .$row["PatientID"]."<br>". "First name and Last name: " . $row["Firstname"]. " ".$row["Surname"]. "<br/>";
$_SESSION['id'] = $row["PatientID"];
$_SESSION['username'] = $row["Firstname"];
$_SESSION['surname'] = $row["Surname"];
$_SESSION['logged_in'] = 2;
header("location: http://localhost/index.php");
die;
}
}else{
foreach($result as $row) {
$_SESSION['id'] = $row["PatientID"];
$_SESSION['username'] = $row["Firstname"];
$_SESSION['surname'] = $row["Surname"];
$_SESSION['logged_in'] = 1;
header("location: http://localhost/index.php");
die;
}
}
}else{
$_SESSION['logged_in'] = 0;
header("location: http://localhost/user.php");
die;
}
?>
<?php
if ($result->num_rows > 0){
header("location: http://localhost/index.php");
}else{
echo "Wrong Username or Password <br />".
'Go back...';
}
?>
You may also create a login_failure.php page and in the else part redirect the user to that page. OR another approach is to pass the value of failure message
header("location: http://localhost/user.php?msg = 1");
and display the message at the top of login box. Get the value of 'msg' in user.php page and apply if condition to display the message.
<div><?php
$msg = $_GET['msg'];
if (isset($msg)) { echo "Wrong username/password"; } ?> </div>
<form action="../login.php" method="post">
<label for="login-username"><i class="icon-user"></i> <b>Username</b> </label><br/>
<input class="form-control" type="text" name="username">
<br/>
<label for="login-password"><i class="icon-lock"></i> <b>Password</b> </label> <br/>
<input class="form-control" type="password" name="password">
<br/>
<button type="submit" class="btn pull-right">Login</button>
</form>

Using PDO and sessions to create a login form

I have created a login-logout form using PDO and php session. Here is the entire code for different pages
LOGIN FORM
<form role="form" class="omb_loginForm" action="login.php" autocomplete="off" method="POST">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<span class="help-block"></span>
<button class="btn btn-lg btn-primary btn-block" name="submit" type="submit">Login</button>
</form>
login.php
<?php
session_start();
if (isset($_POST['submit'], $_POST['email'], $_POST['password']))
{
try
{
$email = $_POST['email'];
$password = $_POST['password'];
$dbhost = "localhost";
$dbname = "abc";
$dbuser = "abc";
$dbpass = "pwd";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM register WHERE `email` = :email AND `password` = :password ";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $_POST['email'], ':password'=> $_POST['password']));
$num=$stmt->rowCount();
if($num > 0)
{
header("location:dashboard.php");
}
else
{
header("location:login_form.html");
}
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
?>
session.php
<?php
$dbhost = "localhost";
$dbname = "abc";
$dbuser = "abc";
$dbpass = "pwd";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
session_start();
$user_check=$_SESSION['login_user'];
$result = $conn->prepare("SELECT * FROM register WHERE email= :$user_check");
$result->execute(array(":usercheck"=>$user_check));
$row = $result->fetch(PDO::FETCH_ASSOC);
$login_session =$row['email'];
$user_id =$row['id'];
$user_passwords = $row['password'];
if(!isset($login_session))
{
$conn = null;
header('Location: login_form.html');
}
?>
dashboard.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
the problem that i am facing is that when the i try to login with the correct credentials the form gets redirected to login_form.html whereas it should go to dashboard.php page.
Your error is :$user_check. Sugget you to change like below.
$result = $conn->prepare("SELECT * FROM register WHERE email = :user_check");
/*^^^*/
$result->execute(array(":usercheck"=>$user_check));
I also see another error in there: I see an undefined index at
$user_check=$_SESSION['login_user'];
Where does 'login_user' come from?

Categories