I have a page in which the user can log in. A php script check the login values.
The problem is, when I enter my details in the form, I get redirected to the .php page but I get a blank screen. When I refresh that screen, it says "Unsuccesfull" because my email and password values aren't set anymore because of the refresh.
Why do I get a blank page after pressing "Log in"?
<!DOCTYPE html>
<html>
<head>
<title>Grippee - Login</title>
<link rel="stylesheet" href="style2.css" />
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<link rel="stylesheet" href="themes/customtheme.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<a class="ui-btn-left" href="index.html" data-icon="back">Terug</a>
<h1><span>Login</span></h1>
<a class="ui-btn-right" href="#" data-icon="info">i & €</a>
</div>
<div data-role="content" data-position="relative">
<div class="loginform">
<form id="loginForm" action="login.php" method="POST">
<span>Email adres:</span>
<input type="text" name="email" id="email"></input>
<span>Wachtwoord:</span>
<input type="password" name="password" id="password"></input>
<input type="submit" value="Login" />
</form>
</div>
</div>
<div data-role="footer" data-position="fixed"></div>
</div>
</body>
</html>
The PHP:
<?php
$email = "";
$password = "";
if (isset($_POST["email"]))
{
$email = $_POST["email"];
echo ($email);
}
else {
echo("Something is wrong");
}
if (isset($_POST["password"]))
{
$password = $_POST["password"];
echo($password);
}
$mysqli = new mysqli('localhost', 'qq', 'qq', 'qq', 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$result = $mysqli->query("SELECT id FROM Consument WHERE email = '$email' AND wachtwoord = '$password'");
$rows = $result->num_rows;
if ($rows == 1)
echo ("Logged in!");
else
echo ("Unsuccesfull!");
?>
the query is not correct.
use this:
$result = $mysqli->query("SELECT * FROM Customer WHERE email = " . $email . " AND wachtwoord = " . $password);
I modified a bit your php. Give a try with it. Even like this is not the best approach but..
<?php
//enable all kind of errors to can debug properly
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$email = "";
$password = "";
if ( isset($_POST["email"]) && isset($_POST["password"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
echo ($email);
echo($password);
$mysqli = new mysqli('localhost', 'qq', 'qq', 'qq', 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$result = $mysqli->query("SELECT * FROM Customer WHERE email = '".$email."' and wachtwoord = '".$password."'");
$rows = mysql_num_rows($result);
if ($rows == 1)
echo ("Logged in!");
else
echo ("Unsuccesfull!");
}
else {
echo("Something is wrong");
}
?>
Related
I am trying to create a working HTML Login Page with a PHP script that compares the login data with the Database.
I have been trying to get this working for some time now but it doesent really work. This is the Error Code I get when I press on the Login Button:
Cannot POST /connectivity.php
I created a Database (called leftover_youth)with XAMPP.
UserNameID
userName
pass
This at the moment the HTML code for the whole page.
<html>
<head lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" name="viewport">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="scripts/app.js"></script>
<link rel="stylesheet" href="css/stylesheet.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title>Project Bootstrap</title>
</head>
<body>
<header>
<div class="navlogo">
<a href="index.html">
<h1 class="Logo">Leftover Youth</h1>
</a>
<a href="index.html">
<img class="logoo" src="img/logoo.png" alt="firstimage">
</a>
</div>
</header>
<div>
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php"> User <br>
<input type="text" name="user" size="40"><br> Password <br>
<input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div>
</body>
</html>
PHP:
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'leftover_youth');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$ID = $_POST['user'];
$Password = $_POST['pass'];
function SignIn()
{
session_start(); //starting the session
if(!empty($_POST['user'])) //checking User data
{
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit'])) { SignIn();
}
?>
You need to check the directory/path of connectivity.php
also move the $ID and $Password in to the post check
if(isset($_POST['submit'])) { SignIn();
$ID = $_POST['user'];
$Password = $_POST['pass'];
}
First of all avoid using mysql which is long back deprecated, instead use mysqli
There are few solutions for your problem.
The way with MySQLi would be like this:
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
To run database queries is also simple and nearly identical with the old way:
// Old way
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
// New way
$query = mysqli_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
I dont know what to do anymore, when i login it's cool and then when i return back it logs me out but cookies arent destroyed, i want on whatever page i go to stay logged on, and yep, SUBMIT buttons i can press it because when i log in its not hidden, please help, im on the edge of losing it, improve my code if its wrong, and i know it is
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","","samp");
if (mysqli_connect_errno())
{
echo "Failed to connect to the database: " . mysqli_connect_error();
die();
}
session_start();
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$userName = isset($_POST["username"]) ? $_POST["username"] : null;
$userPass = isset($_POST["password"]) ? $_POST["password"] : null;
$hashedPass = hash('whirlpool', $userPass);
$query = "SELECT Ime FROM Igraci WHERE Ime = '$userName' AND Lozinka = '$hashedPass'";
$result = mysqli_query( $con, $query);
$row = mysqli_fetch_array($result);
if($row)
{
$session = md5($userName.$hashedPass);
mysqli_query($con, "UPDATE Igraci SET session = '$session' WHERE Ime = '$userName' AND Lozinka = '$hashedPass'");
setcookie("login", $userName,time()+3600);
echo "You are now logged in with hash: ".htmlspecialchars($_COOKIE["login"]). ' logout?';
header('index.php');
}
else
{
die('Account has not been found.');
}
}
if(isset($_GET['logout']))
{
setcookie("login", "", time()-60);
exit(); # stop executing here
header('index.php');
}
if(isset($_COOKIE["login"]) && mb_strlen(isset($_COOKIE["login"]) == '32'))
{
$session = $con->real_escape_string($_COOKIE["login"]);
$query = "SELECT Ime FROM Igraci WHERE session = '$session' LIMIT 1";
$result = mysqli_query( $con, $query); $row = mysqli_fetch_array($result);
if($row['Ime'])
{
echo "User is already logged in with username ".$row['Ime']. " and hash: ".htmlspecialchars($_COOKIE["login"]). ' logout?';
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Roleplay Factory User Control Panel</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Welcome, please login to your account.</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" placeholder = "Username" name="username">
<input type="password" placeholder = "Password" name="password">
<input type="submit" name="login_button" value="Login">
</form>
<div class="footer">
<p>roleplay factory © 2016 all rights reserved</p>
</div>
</body>
</html>
update your code line
header('index.php');
to be
header('location:index.php');
I want to create a working login form. Here's what I have done and this displays cannot select db.
Edited login.php file
<?php
error_reporting(E_ALL);
//Connection Variables:
$dbhost = "localhost";
$dbname = "";
$dbuser = "";
$dbpass = "";
try{
//Connection to SQL:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
//Error messagin enabled:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$user = '';
$pass = '';
$sum = 0;
$error_msg = "Please type a username and a password";
if(isset($_POST['login']))
{
//Start a session:
session_start();
$user = $_POST['email'];
$pass = $_POST['password'];
if(empty($user) && empty($pass))
{
echo $error_msg;
$pass = '';
}
if(empty($user) || empty($pass))
{
echo $error_msg;
$user = '';
$pass = '';
}
if(!empty($user) && !empty($pass))
{
//SQL:
$query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
$query->bindParam(":u", $user);
$query->bindParam(":p", $pass);
//Execute query:
$query->execute();
$number_rows = $query->fetch(PDO::FETCH_NUM);
if($number_rows>0)
{
echo $user;
$_SESSION['usern'] = $user;
$_SESSION['passw'] = $pass;
header("Location: ./pages/home.php");
}
//echo $user;
else
{
echo "Invalid username or password";
header("Location: index.html");
}
}
}
if(!isset($_POST['login']))
{
echo "Login button not clicked";
}
?>
I read more and more articles on this, still I can't find a solution.
Edited HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Signin for OTMS</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form action="login.php" method="post" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
Please help me to find what is the error.
I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.
This is the error I'm getting now:
database name- otmsdb
table name- login
email, passowrd,
button name- login
Sir, your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you:
Source: Udemy Online course.
EDIT: use this code, and change the variables into yours
<?php
session_start();
if(isset($_POST['login'])){
$errmsg_arr = array();
// configuration
$dbhost = "localhost";
$dbname = "your database name";
$dbuser = "your username";
$dbpass = "your password";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// new data
$user = $_POST['username'];
$password = $_POST['password'];
if($user == '') {
$errmsg_arr[] = 'You must enter your Username';
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
}
// query
if (!$errmsg_arr) {
$result = $conn->prepare("SELECT * FROM login WHERE username= :user");
$result->execute(['user' => $username]);
$row = $result->fetch(PDO::FETCH_NUM);
if($row && password_verify($_POST['password'], $row['password']) {
$_SESSION['user'] = $row;
header("location: ./pages/home.php");
exit;
}
else{
$errmsg_arr[] = 'Username and Password are not found';
}
}
}
?>
HTML FORM:
<body>
<?php foreach($errmsg_arr as $msg): ?>
<?=htmlspecialchars($msg, ENT_QUOTES) ?><br>
<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password" value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>
</body>
Suggestions:
echo mysql_error() to determine why the error is occurring:
mysql_select_db("$db_name") or
die("cannot select DB: " . mysql_error());
Stop using deprecated functions " mysql_connect()", "mysql_query()" and friends. You'd be much better served with mysqli instead.
Use Prepared Statements instead of building your "select" directly from your POST parameters.
Can anyone see the error in this code as the code is only giving me back :
the name does not exist
It was all working fine now it does not.
If anyone can spot it please and correct me as I am still new to this.
<?php
// see if the form has been completed
include_once("php_includes/check_login_status.php");
include_once("php_includes/db_conx.php");
// Initialize any variables that the page might echo
$username = "";
$firstname = "";
$surname = "";
$gender = "Male";
$country = "";
$weight = "";
$height = "";
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
}
$sql = "SELECT * FROM users WHERE username='$username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$username = $row ["username"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$email = $row["email"];
$gender = $row ["gender"];
}
if (isset($_POST['submit'])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$weight = $_POST['weight'];
$height = $_POST['height'];
$email = $_POST['email'];
$gender = $_POST['gender'];
mysql_connect ("host","****","*****"); mysql_select_db('db_k1003140');
// check if that user exist
$exists = mysql_query ("SELECT * FROM users WHERE firstname='" . $username . "'") or die ("query cant connect");
if (mysql_num_rows ($exists) != 0) {
// update the description in the database
mysql_query("UPDATE users SET firstname='$firstname', surname='$surname', weight='$weight', height='$height' WHERE username='$username'") or die ("update could not be applied");
echo "successful";
} else echo "the name does not exist";
}
?>
Here is the HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Profile Update: <?php echo $u; ?></title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/main.js"></script>
<script src="js/javascript.js"></script>
<script src="js/ajax.js"></script>
<style type="text/css">
#updateform{
margin-top:24px;
}
#updateform > div {
margin-top: 12px;
}
#updateform > input {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
</style>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<div id="usernamecss"> Username: <?php echo $username; ?></div>
<form action="update.php" method="POST" id="updateform">
<div>
<div>First Name: </div>
<input id="firstname" type="text" name="firstname" value="<?php echo $firstname?>" maxlength="16">
<div>Surname: </div>
<input id="surname" type="text" name="surname" value="<?php echo $surname?>" maxlength="16">
<div>Weight: </div>
<input id="weight" type="text" name="weight" value="<?php echo $weight?>" >
<div>Height: </div>
<input id="height" type="text" name="height" value="<?php echo $height?>" >
<p> <input type="submit" name="submit" id="submit" value="Update Description"></p>
Go to Profile
</div>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
Just a guess you comparing username field with firstname,
SELECT * FROM users WHERE firstname='" . $username . "'";
While it needs to be,
SELECT * FROM users WHERE username='" . $username . "'";
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I looked on http://www.phpportalen.net/wiki/index.php?page=Enkel+inloggning+med+MySql+och+sessioner to how to do a simple login.
But when i try to login now it says that the username or password is wrong. So Im guessing something is not right in my control dokument, where im checking the usernamne and password to the database.
In the exampel i looked on they have it all in the same page, so im guessing I need to change more than i thougt.
This is the code in the loginside:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="stylesheet.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if(!isset($_SESSION["sess_user"])){
if(isset($_GET['badlogin'])){
echo "Fel användarnamn eller lösenord, försök igen!";
}
?>
<form method="post" action="check.php">
<p>User</p>
<input name="user" type="text" />
<p>Password</p>
<input name="password" type="text" />
<input name="logIn" type="submit" value="Log in" />
</form>
<?php
}
else{
header("Location: admin.php");
}
?>
</body>
</html>
And this is the code in my controlside:
<?php
session_start();
?>
<?php
function db_escape($post){
if(is_string($post)){
if(get_magic_quotes_gpc()){
$post = stripslashes($post);
}
return mysqli_real_escape_string($post);
}
foreach($post as $key => $val){
$post[$key] = db_escape($val);
}
return $post;
}
if(isset($_POST["logIn"])){
// Connect to db
$dbConn = mysqli_connect("localhost","sabe0011","lösen","sabe0011");
$dbConn->set_charset("utf8");
// Check connection
if(mysqli_connect_errno($dbConn)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$_POST = db_escape($_POST);
$checkUserSQL = mysqli_query($dbConn, "SELECT * FROM Users WHERE User ='{$_POST['user']}' AND Password ='{$_POST['password']}'");
if(mysqli_num_rows($checkUserSQL) == 0){
header("Location: login.php?badlogin=");
exit;
}
$_SESSION['sess_id'] = mysqli_store_result($checkUsersSQL, 0);
$_SESSION['sess_user'] = $_POST['user'];
header("Location: admin.php");
exit;
}
?>
Your parameters in your query should be escaped like:
$checkUserSQL = mysqli_query($dbConn, "SELECT * FROM Users WHERE User =" . $_POST['user'] . " AND Password = " . $_POST['password']);
But in term of security, you have to see at the prepared query here.