Create session using username and password. - php

I need to created login/registration system. User can submit his details and its works fine , but I struggle to create session/log in user with username and password he submitted. When user put any detalis I got info: Notice: A session had already been started and results of that is anyone can get access to restricted sub page. Its seems like php code not retrieve recorded username and passwords. Thanks for any hint.
<form form action=" <?php echo $self; ?>" method="POST">
<div>
<label for="user">Username:</label>
<input type="text" name="username" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" />
</div>
<input type="submit" name="submit" value="submit" />
if(isset($_POST['submit'])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$user=$_POST['username'];
$pass=$_POST['password'];
$file = fopen('filewriting.txt', 'r');
$clean = array();
while (!feof($file)) {
$clean = fgets($file);
}
fclose($file);
$clean['username'] = $user;
$clean['password'] = $pass;
if($user == $clean['username'] && $pass == $clean['password'] )
{
session_start();
$_SESSION['sess_user'] = $user;
}
} else {
echo 'Invalid username or password!';
}
} else {
echo 'All fields are required!!!';
}

Related

PHP Form Login - Send Error Message

I have this line of code and I am trying to send an error message if the username password combination don't match, the thing is the message displays when I access the page, even before i enter a username and password. how do I make the message appear ONLY after login failed?
Thanks!!
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($user == "someusername") && ($pass == "somepassword"))
{
include("../securedfile.php");
}
else{
$message = "Invalid User/Password - Please Try Again";
echo "<script type='text/javascript'>alert('$message');</script>";
}
if(isset ($_POST))
{?>
<div class="secure">
<form method="POST" action="secure.php">
username:<input class="user" type="text" name="user"></input><br/><br/>
password:<input class="pass" type="password" name="pass"></input><br/><br/>
<button class="submit" type="submit" name="submit">SUBMIT</span></button>
</form>
</div>
<?}
}
?>
There is the parenthesis problem with the 'else', then the form is calling secure.php instead of calling itself, there's no isset...The rewritten code below would be a better way of doing it. And have checked it, it works. (The name of this whole file - new.php)
<div class="secure">
<form method="POST" action="new.php">
username:<input class="user" type="text" name="user"></input><br/><br/>
password:<input class="pass" type="password" name="pass"></input><br/><br/>
<button class="submit" type="submit" name="submit">SUBMIT</span></button>
</form>
</div>
<?php
// checking the user
if(isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "someusername" && $pass == "somepassword")
{
include("../securedfile.php");
}
else
{
$message = "Invalid User/Password - Please Try Again";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>

How to push element down when another is added

<form id="password_form" action="" method="post">
Username: </br>
<input type="text" name="login_username"></br>
Password:</br>
<input type="password" name="login_password">
</br>
<input type="submit" name="login" value="Log in">
</form>
//form validation now occurs
<?php
if (isset($_POST['login']))
{
$username = trim($_POST['login_username']);
$password = trim($_POST['login_password']);
//checks if correct credentials were given
$login = login($username, $password);
if ($login === FALSE)
{
$errors[] = 'That username/password combination is incorrect';
$errors_1 = output_errors($errors);
echo "<div id='errors'> $errors_1</div>";
}
}
?>
Above is my code. After the user submits the form, I check to make sure the user has provided the correct credentials. If not, then an error message is added to the $errors array and is outputted. I want the errors to be outputted above the form and the form to be moved down proportionally. I've tried locating the errors array above the form and increased the margin and padding but that did not work. Any suggestions?
If you are using jQuery and you have a separate html and php (MVC)
define a div in the form called error_container <div id="error_container"></div>
then from your PHP echo the response .
$html = "<div id='errors'>$errors_1</div>";
echo json_encode($html);
in jQuery ajax success
success:function(result){
$("#error_container").html(result);
}
if you are using only PHP and your php and html is in same page
in your view set if $error_1 is set , echo the error
//form validation now occurs
<?php
if (isset($_POST['login']))
{
$username = trim($_POST['login_username']);
$password = trim($_POST['login_password']);
//checks if correct credentials were given
$login = login($username, $password);
if ($login === FALSE)
{
$errors[] = 'That username/password combination is incorrect';
$errors_1 = output_errors($errors);
}
}
?>
<!-- check is variable isset -->
<?php if(isset($errors_1)) { ?>
<div id='errors'><?php echo $errors_1; ?></div>
<?php } ?>
<form id="password_form" action="" method="post">
Username: </br>
<input type="text" name="login_username"></br>
Password:</br>
<input type="password" name="login_password">
</br>
<input type="submit" name="login" value="Log in">
</form>

Cant seam to get PHP login to work, used to work but slightly changed it

I made a login that worked perfectly, but now im copying the original and editing it to work on another one of my web projects and it jsut dosnt seam to want to work, any help would be appreciated!
Here is the login that worked:
<?php
session_start();
include('../includes/connect-db.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
</head>
<body>
<div>Message would go here</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM users WHERE user_username = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
</head>
<body>
<div>Login form would go here</div>
</body>
</html>
<?php } ?>
And here is the login im trying to get to work (some more info about it under the code):
<?php
//Start Session
session_start();
//Connect To DataBase
include($_SERVER['DOCUMENT_ROOT'].'includes/connect-db.php');
//Login
if (isset($_SESSION['logged_in'])) {
header('Location: http://localhost/logged-in.html');
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM admins WHERE admin_username = ? AND admin_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: http://localhost/techbite/logged-in.html');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
//Page Content
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
//Select Theme
include($_SERVER['DOCUMENT_ROOT'].'themes/theme-select.php');
}
?>
Keep in mind that database connection is successful, the login form appears but just dosnt seam to log in or show an error when nothing is entered/wrong credentials, everything else works perfect, including importing the form into the theme with $content.
Here is the connect-db.php:
<?php
//Connect To Database
try {
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
} catch (PDOException $e) {
exit('Database error, could not connect.');
}
?>
What iv done here is included the theme:
include($_SERVER['DOCUMENT_ROOT'].'/themes/theme-select.php');
And inside the theme where i want the content i have:
<?php echo($content); ?>
and in the login php file i have this which will be put into the php theme file:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
I hope someone can help, hopefully its something small i have missed!
Thanks for any help and let me know if anything else is needed.
Kind Regards,
Hayden.
it's not showing an error because
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
is all just a string, and the <?php ?> sections inside this string are never parsed by the php interpreter. View the page source of your login page and you should see them there.
If you're set on using this $content variable and the theme-select.php file, try changing it to this:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>';
if (isset($error)) {
$content .= '<small style="color:#aa0000">'.$error.'</small>';
}
As for why it's not logging in, it's a silly question, but have you created a table in your database named admins and a record there with a username and password set?
Try replacing
$num = $query->rowCount();
with
$num = count($query->fetchAll(PDO::FETCH_ASSOC));
UPDATE
Just noticed this...
if (isset($_POST['username'], $_POST['password'])) {
should be
if( isset($_POST['username']) && isset($_POST['password']) ) {
I would add an else condition here to display an error message of some description
UPDATE 2
Slight modification to your connect.php
try {
// create a new instance of a PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
I fixed it!
i knew it would be something so small and simple, it was the form action which was set to the wrong file name, it was set to index.php instead of login.php.
Thank you to everyone for your help! :)

Show username after login [duplicate]

This question already has answers here:
Undefined variable: $_SESSION
(4 answers)
Closed 1 year ago.
So I'm trying to show an users username after he or she has logged in but I just can't get it to work...
Here are the codes I am using:
First off, an user has to log in.
<div>
<form method="POST" action="login.php">
<h2>LOGIN</h2>
<input type="text" placeholder="Username" name="username" />
<input type="password" placeholder="Password" name="password" />
<br />
<input class="btn btn-large btn-primary" type="submit" name="login" value="Log In" />
</form>
</div>
After using the form, this sript will load, this is 'login.php':
<?php
session_start();
if(!$_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Go away.<br /><br />";
exit();
}
if(mysql_connect('localhost', 'root', '')) {
if(mysql_select_db('users')) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$zoekresultaat = mysql_query($query);
if($zoekresultaat = mysql_affected_rows() > 0) {
$record = mysql_fetch_assoc($zoekresultaat);
$_SESSION['login'] = true;
$_SESSION['username'] = $record['username'];
header('location: dashboard.php');
} else {
header('location: loginerror.php');
}
exit();
} exit(); {
echo "Can't find database.";
}
} else {
echo "Can't connect to database.";
}
?>
When this is done, the user gets redirected to 'dashboard.php' which is the following:
<?php include "includes/menu.php";?>
<div id='content'>
<h1><strong>Welkom <?php echo $_SESSION['username']; ?></strong></h1>
<p></p>
</div>
<?php include "includes/foot.php";?>
Problem is when I try to login I get the following error:
Notice: Undefined variable: _SESSION in D:\xampp\htdocs\NGP\dashboard.php on line 5
I'm really lost and hoping to get some answers here!
Thanks in advance!
Just include session_start(); line in the common include file.

Having trouble authenticating users

I'm having a lot of trouble with the $_SESSION variable. I'm trying to create a way for users to log in and out. I can log a user in but i don't seem to be able to maintain the session when i switch page. When the user correctly logs in they are taken to profile.php. But if i return to index.php the following error is printed:
Notice: Undefined index: login in /Applications/MAMP/htdocs/www/Shared sites/userlogreg/index.php on line 3
I'm quite new to this but from looking on SO and elsewhere i can't seem to figure it out. Any help would be appreciated.
index.php
<?php
session_start();
if ($_SESSION['login'] == 1) {
echo "<h1>Logged in!</h1>";
} else {
echo "<h1>Not logged in</h1><br/>";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Index page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="POST">
<div>
<label for="emailSignIn">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordSignIn">Password:</label>
<input type="password" name="password" placeholder="Password" required="required" />
</div>
<input type="submit" name="submit" value="Sign in" />
</form>
<h2>Register</h2>
<form action="register.php" method="POST">
<div>
<label for="firstnameRegister">First name:</label>
<input type="text" name="firstname" placeholder="First name" required="required" />
</div>
<div>
<label for="lastnameRegister">Last name:</label>
<input type="text" name="lastname" placeholder="Last name" required="required" />
</div>
<div>
<label for="emailRegister">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordRegister">Password:</label>
<input type="password" name="password" placeholder="Password" required="required">
</div>
<input type="submit" name="submit" value="Create account" />
</form>
</body>
</html>
login.php
<?php
$email = sanitize_input($_POST['email']); //echo "Sanitized email: ".$email; echo "<br/>";
$password = $_POST['password']; //echo "Inputted password: ".$password; echo "<br/>";
if ((!isset($email)) || (!isset($password))) {
// VISITOR NEEDS TO ENTER AN EMAIL AND PASSWORD
//echo "Data not provided";
} else {
// CONNECT TO MYSQL
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
//echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
}
}
// SELECT THE APPROPRIATE DATABASE
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
//echo "Cannot select database.";
exit;
} else {
}
// GET THE USER'S UNIQUE SALT FROM THE DATABASE
$unique_salt = mysqli_query($mysql, "select uniqueSalt from user where email = '".$email."'");
$row = mysqli_fetch_array($unique_salt);
//echo "Salt: ".$row['uniqueSalt']; echo "<br/>";
// HASH THE PASSWORD
$iterations = 10;
$hashed_password = crypt($password,$row['uniqueSalt']);
for ($i = 0; $i < $iterations; ++$i)
{
$hashed_password = crypt($hashed_password . $password,$row['uniqueSalt']);
}
//echo "Password entered by user: ".$hashed_password; echo "<br/>";
$user_db_password = mysqli_query($mysql, "select password from user where email = '".$email."'");
$row = mysqli_fetch_array($user_db_password);
//echo "User's password: ".$row['password']; echo "<br/>";
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashed_password."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
//echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
session_start();
$_SESSION['login'] = 1;
$_SESSION['email'] = $email;
$_SESSION['errors'] = "";
header("location:profile.php");
//echo "<h1>Login successful!</h1>";
//echo "<p>Welcome.</p>";
//echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
session_start();
$_SESSION['login'] = '';
header("location:index.php");
//echo "<h1>Login unsuccessful!</h1>";
//echo "<p>The email and password combination entered was not recognized</p>";
}
// CLEAN THE INPUT
function sanitize_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Change this line:
if ($_SESSION['login'] == 1) {
..to this:
if (isset($_SESSION['login']) && $_SESSION['login'] == 1) {
That way, you check if 'login' is set before you access it.

Categories