I have written php script for user login but instead of displaying the result the whole script is being displayed.I have given a .php file link as an action for the login form.
I am using xampp with php and mysql running do I need anything else?
the code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Ch</title>
<meta name="description" content="education,India,College search in india,score evaluator" />
<meta name="author" content="RAJATEJAS" />
<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<style type = "text/css">
user_login , input
{
display = inline;
}
</style>
</head>
<body>
<div>
<header>
<h1>Ch</h1>
</header>
<nav>
<p>Home</p>
<p>Contact</p>
</nav>
<div class = "user_login_form">
<form action = "chalo_login.php" method="post">
<label>Username:</label><input id = "username" type = "text" name = "username" autofocus placeholder="Enter Username"/><br />
<label>Password:</label><input id = "password" type = "password" name = "password" placeholder="Enter Password"/><br />
<input name = "submit" type = "submit" value = "Login" />
</form>
</div>
<footer>
<p>© Copyright by RAJATEJAS</p>
</footer>
</div>
</body>
</html>
<?php
session_start();
$_POST['username'];
$_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost","root","");
mysql_select_db("phplogin") or die("could not find database");
$query = mysql_query(SELECT * FROM users WHERE username = "$username");
$numrow = mysql_num_rows($query);
if ($numrows !=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row["username"];
$dbpassword = $row["password"];
}
if($username == $dbusername && $password == $dbpassword)
{
echo "You are logged in! ;
Click here";
$_SESSION["username"] = $dbusername;
}
else
{
echo "Incorrect password";
}
}else{die("Account does not exists");}
}
else
{
die ("Please enter details");
}
?>
You've got a few errors in your code, but I don't know if they're what are causing your problems.
Firstly in your CSS user_login should be #user_login to select elements with the ID "user_login". Then, display = inline; should be display: inline;.
In your PHP...
$_POST['username'];
$_POST['password'];
...doesn't do anything. I think you should have
$username = $_POST['username'];
$password = $_POST['password'];
And as Ethan mentioned in the comments above, your quotation marks are messed up:
echo "You are logged in! ;
Click here";
...should probably be:
echo "You are logged in! Click here";
(Escape your quotation marks inside quotation marks using a backslash).
Fix those errors and see if it works then...
Also: as LeleDumbo says above, make sure the page is being loaded through Apache rather than opened as a file. The URL should begin with something like 127.0.0.1 or localhost. If not, just put 127.0.0.1 into your address bar and browse to your file in the list that appears.
Another error- your SELECT statement needs to be a string:
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
Variables $username and $password are not assigned
if(isset($_POST['username'])
{
$username=$_POST['username'];
}
if(isset($_POST['password'])
{
$password=$_POST['password'];
}
and the select the correct database in the comment above you are saying that your database name is also "users" but you have selected "phplogin"
Related
I'm trying to make a login system with hashed passwords.
What is supposed to happen is after I click on the submit button a session should be created and I should be redirected to home.php. If input data doesn't match the data inside the database I should get "Error 1" or "Error 2" alerts.
My problem is that when I click on a submit button all that happens is that I get redirected to login.php. I get no errors and no alerts, only blank screen with login.php URL.
I'm trying to figure how to make the password_verify() part work. Any kind of help is appreciated.
Picture of database: https://imgur.com/a/BXiHBN4
Picture of what happens after a login attempt: https://imgur.com/a/qKZ1tsi
Form code:
<html>
<head>
<title> Login now! </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<header>
<div class="alignRight">
Register
</div>
<div class="alignLeft">
Contact us
About us
News
</div>
</header>
<h1> Welcome back! </h1>
<h2> Log in to continue with your work. </h2>
<form name="login-form" id="login-form" action="login.php" method="post">
<input class="_40" type="text" name="username" pattern="[a-zA-Z0-9_]{1,15}"
placeholder="Username" required />
<br />
<input class="_40" type="password" name="pwd" placeholder="Password" required />
<br />
<input id="loginSubmitButton" type="submit" value="Submit" />
</form>
</body>
</html>
PHP code:
<?php
session_start();
$servername ="localhost";
$username = "root";
$password = "";
$link = mysqli_connect($servername, $username, $password);
mysqli_select_db($link, "users");
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pwd = mysqli_real_escape_string($link, $_POST["pwd"]);
$query = "SELECT * FROM users WHERE Username = '$username'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);
if(($result->num_rows > 0))
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($pwd, $row["Hash"]))
{
$_SESSION["username"] = $username;
header("location:home.php");
}
else
{
echo '<script>alert("Error 1")</script>';
}
}
}
else
{
echo '<script>alert("Error2")</script>';
}
?>
I think I see the problem.
It looks like you're probably fetching the only row from the results before the if
$row = mysqli_fetch_assoc($result);
Then when you fetch again here, there's nothing left to fetch.
if(($result->num_rows > 0))
{
while($row = mysqli_fetch_array($result))
(I'm assuming the query will only return one row since username is unique.)
I'm trying to help out my friend with a problem consisting PHP and MySQL. It's been about 3-4 months since I've done PHP/MySQL at all, so I need some help identifying the problem. The following code produces the error informing the user that localhost has redirected too many times:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login
</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
//Checking is user existing in the database or not
$md5pass = md5($passowrd);
$query = "SELECT * FROM `users` WHERE username='$username' and password='$md5pass'";
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Log In
</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet?
<a href='registration.php'>Register Here
</a>
</p>
</div>
<?php } ?>
</body>
</html>
Yes, I do realize the security issues about the code. I will inform about those issues to my friend, but for now, I only want to figure out why the code is redirecting many times, while it should be redirecting only once.
I suspect that it's something related to the fact that the header() function is used after multiple outputs, or the php section isn't closed properly.
There was an if statement in index.php that contained a header() function that led back to the login page. It was basically a loop.
When i select my button in the form with the link to the processing page for the login it just returns a server error 500, i have not encountered this before and have had no luck on google.
Here is my HTML markup on the login page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Administrator Login</title>
</head>
<body>
<div class="container">
<div class="header"><img src="IMAGES/LOGO.png" alt="Insert Logo Here" name="Insert_logo" width="" height="90" id="Insert_logo" style="background-color: #; display:block;" />
<!-- end .header --></div>
<div class="content">
<form action="loginProcess.php" method="post" class="loginForm">
<input type="text" id="username" name="username" placeholder="Enter Username" required>
<input type="password" id="password" name="password" placeholder="Enter Password" required>
<button type="submit" id="loginBTN" >Login</button>
</form>
</div>
</body>
</html>
And here is the code for my php process
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//stores the search data
$username = $_POST['username'];
$password = $_POST['password'];
//checks to see if it is empty or null
if(isset($username) && !empty($username) && (isset($password) && !empty($password))){
require('includes/dbconx.php');
//escapes all special characters that could break database
$pword = mysqli_real_escape_string($con, $password);
$uname = mysqli_real_escape_string($con, $username);
//searchq stores the cleaned up search data
//create a variable to store a wildcard SQL statement
$sql = mysqli_query($con, "SELECT * FROM login WHERE username = '%$uname%' AND password = '%$pword%' ");
}//end statement
//if no data is inserted it will putput this
else{
echo("Please enter Login details!");
//this will kill the connection
die;
}
//end else
$result = $con->query($sql);
//if it finds no matching data it informs the user and kills the DB connextion
if(mysqli_num_rows($result) == 0){
echo("<p>No record found or password doesn't match! </p>");
die;
}
else{
header('Location: adminPage.php');
?>
</body>
</html>
Here is my connection, this works for the other pages as it should this.
<?php
//connects to my music database
$con=mysqli_connect("localhost","root","root","music");
//if it fails to connect it outputs this with an error number
if(mysqli_connect_errno()) {
echo "failed to connet to MYSQL:".mysqli_connect_error();
}
?>
Got time for that Beer?
This query is incorrect, you use the % character only when using the LIKE syntax, so query should be
$sql = mysqli_query($con, "SELECT *
FROM login
WHERE username = '$uname'
AND password = '$pword' ");
If you format your code more consistantly it will also help in spotting errors.
And as in my answer to your last question, check for errors after all mysqli_ calls. During development it will save you much time, as thats when we developers make little bobo's
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// this would be better at the top of the script
require('includes/dbconx.php');
// why do 2 steps when one would do
// also you have not checked these actually exist
// until the IF that follows these 2 lines
//$username = $_POST['username'];
//$password = $_POST['password'];
// empty() does an isset already so you only need the empty()
if( !empty($username) && !empty($password)){
$pword = mysqli_real_escape_string($con, $_POST['password']);
$uname = mysqli_real_escape_string($con, $_POST['username']);
$sql = mysqli_query($con, "SELECT *
FROM login
WHERE username = '$uname'
AND password = '$pword'");
// always check status after mysqli_query and other calls
// and at least output the error message
if ( $sql === FALSE ) {
echo mysqli_error($con);
exit;
}
} else {
echo("Please enter Login details!");
die;
}
$result = $con->query($sql);
if(mysqli_num_rows($result) == 0){
echo("<p>No record found or password doesn't match! </p>");
die;
} else {
header('Location: adminPage.php');
// header Location: shoudl always be followed by an exit;
// as header does not stop execution
exit;
} // add missing closing bracket
?>
</body>
</html>
I followed a tutorial to create a simple login system using php. I have installed wampserver and created the database from phpmyadmin panel. It's not working and I belive it's a problem with the servers. When I created the database the server that appeared there was mysql wampserver and in the tutorial was localhost. I changed the name of the server in the config.inc.php to localhostbut is still not working. When I click the login button it takes back to the index page of wampserver. I will share my code maybe someone can find the bug because I can't figure it out what I'm doing wrong.
dbConnect.php
<?php
$dbCon = mysqli_connect("localhost", "root", "", "tests");
?>
user.php
<?php
session_start();
if (isset($_SESSION['id'])) {
// Put stored session variables into local PHP variable
$uid = $_SESSION['id'];
$usname = $_SESSION['username'];
$result = "Test variables: <br /> Username: ".$usname. "<br /> Id: ".$uid;
} else {
$result = "You are not logged in yet";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $usname ;?> - Test Site</title>
</head>
<body>
<?php
echo $result;
?>
</body>
</html>
first.php
<?php
session_start();
if (isset($_POST['username'])) {
// Include the databas connection script
include_once("dbConnect.php");
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
//$usname = mysqli_real_escape_string($dbCon, $usname);
//$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT id, username, password FROM members WHERE username = '$usname' AND activated = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[1];
$dbPassword = $row[2];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic login system</title>
</head>
<body>
<div id="wrapper">
<h1>Simple PHP Login</h1>
<form id="form" action="index.php" method="post" enctype="multipart/form-data">
Username: <input type="text" name="username" /> <br />
Password: <input type="password" name="password" /> <br />
<input type="submit" value="Login" name="Submit" />
</form>
</body>
</html>
What RhapX is trying to explain is that your form action tells the form where to post the data. Currently, you have
<form id="form" action="index.php" method="post" enctype="multipart/form-data">
That means once a user hits Submit its going to send them to index.php and will send the $_POST data with them. But you are saying that first.php is the file that is actually doing all the work, so you need to send the user and $_POST data to first.php instead. Change it to:
<form id="form" action="first.php" method="post">
(Change the action to first.php and just get rid of the enctype -- it might be correct, but it's completely unnecessary and I've seen it cause problems for some.)
Alright, SO. After about five hours of sifting through potential duplicates and applying would-be solutions to my project and even downloading a PHP IDE to make sure that my syntax is all nice and tidy for everyone.. I am finally at the point where I need some advice.
My two problems (which may be related):
When someone logs in, successfully with the test parameters I have stored in the DB, they are not redirected (maybe my if statement is not correct?)
When the page loads without first attempt, my "wrong password - username combination" message is displaying. I'm fairly certain as to why but not too sure how to fix it.
<?php session_start(); // this line of code has been added by the instruction of a comment.
if(isset($submit)) {
$username = $_POST['username'];
$password = $_POST['password'];
}
$con = mysqli_connect("***","***","***","***");
$S_username = mysqli_real_escape_string($con, $username);
$S_password = mysqli_real_escape_string($con, $password);
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$S_username' AND `password` = '$S_password'");
if(!$sql) {
die(mysqli_error($con)) ;
}
$check_again = mysqli_num_rows($sql);
if($check_again == 1) {
session_start(); // this line of code has been deleted
$_SESSION['logged in'] = TRUE;
$_SESSION['username'] = $S_username;
header("Location: http://terrythetutor.com/submitvideo.php");
}
else {
echo "Your username and password combination was not recognised. Please try again." ;
}
?>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php include_once 'googleanalytics.php'; ?>
<body>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<h1 align="center">Please login to access restricted files</h1>
</br>
</br>
</br>
</br>
<div align="center">
<form action = "login.php" method = "post">
Username: <input type = "text" name = "username"></br></br>
Password: <input type = "password" name = "password"></br></br>
<input type = "submit" value = "Login" name="submit">
</form>
</div>
</body>
</html>
Any and all feedback is welcomed. Thank you.
use session_start(); only once and at the top ..