PHP Login Can't login to index.php - php

Why can't I login to my index.php page its just getting stucked in my login.php page. Please help. Thanks.
<?php
session_start();
$conn = new PDO('mysql:host = localhost;dbname=userdb','root','');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->prepare("SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
$query->execute();
$count = $query->fetchColoumn();
if ($count == 1){
$_SESSION['username'] = $username;
header("location : index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "?" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
where could probably my mistake? on my PDO? on my prepared statement? TIA

1)form action missing.
2)isset($_POST['login']) wrong name checking in if condition.
3)prepared statement have lots of issue.
try something like this
<?php
session_start();
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "userdb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM tbl_account WHERE username =? AND password =? ");
$stmt->bind_param('ss',$username,$password);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $get_result->num_rows;
$stmt->close();
$conn->close();
if ($row_count>0){
$_SESSION['username'] = $username;
header("location:index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "login.php" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>

its syntax to use an exit(); after any header('location [...]') calls, you're missing this in your code which could be the reason why your page does nothing.
Also, I'd really like to touch up on some security notes: what the hell is that?
PDO has pre-written functions to allow you the full dynamics of a connection with security, they are there to be used; as it stands, your SQL statement is a security risk as you're directly inserting untrusted data into a statement without stripping it of injections.
Heres an example you could use to secure this:
class DB extends PDO
{
function __construct(
$dsn = 'mysql:host=localhost;dbname=kida',
$username = 'root',
$password = 'root'
) {
try {
parent::__construct($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($statement, array $parameters = array())
{
$stmp = parent::Prepare($statement);
$i = 1;
foreach($parameters as $parameter) {
$stmp->bindParam($i, $parameter);
$i++;
}
$stmp->execute();
return $stmp->FetchAll();
}
}
$Con = new DB();
$username = "example";
$row = $Con->query("SELECT * FROM table WHERE username = ?", [$username]);

You have wrongly used prepared statement.
You should write,
$query = $conn->prepare("SELECT COUNT('userID') FROM REGISTRY WHERE name = ? AND password' = ?");
$query->bindParam(':name', $username);
$query->bindParam(':password', $password);
$query->execute();
$result_rows = $query->fetchColumn(); // get result
Check this link for more detail.
Suggestion:- also add exit; after header tag to stop execution of afterward code.

try and change this code to
"SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
put semicolon inside the quotes and on the outside as well
"SELECT userID FROM tab1_account WHERE username='$username' AND password='$password';";

Related

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>

mysqli_num_rows return 0 always

here am trying to get username and password from the database and if their result is found then redirect to some page but mysqli_num_rows returns 0 always i dunno why `
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `login` WHERE username = '$username' AND password = '$password'";
$run = mysqli_query($con,$query);
if (mysqli_num_rows($run) == 1) {
header("location: login.php");
}}?>
`
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ornament"; // My local DB Name
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = "test"; // $_POST["username"] value
$password = "test"; // $_POST["password"] value
$sql = "SELECT * FROM `ornament` WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
echo "correct";
} else {
echo "wrong";
}
mysqli_close($conn);
?>
</body>
</html>
OUTPUT:
correct
I have a database name and table name are same, But for me it's working fine.
NOTE: Please check the whether you are using correct password while getting from POST.
Any how you got a solution, Have a great day
Thanks
Muthu

SQL INSERT TROUBLE

I'm sitting infront of this code for 2 hours i cant figure out whats wrong :(
I've been trying to have a html form which calls the php function to insert the information from the form into the database but for some reason does not work :/
here is my form code :
<?php include 'connection.php'; ?>
<html>
<body>
<form action="user_create.php" method="POST">
username: <input type="text" name="username"/>
password: <input type="text" name="password"/>
email: <input type="text" name="email"/>
<input type="submit" name='submit' value="user_create"/>
</form>
</body>
</html>
database connection
<?php
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
?>
my php function
<?php include 'connection.php';?>
<?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$query = mysql_query("INSERT INTO users( username,password,email,type)
VALUES ('$username', '$password', '$email','1')");
mysql_query($query);
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else
{
echo '<script type="text/javascript">alert("jo");</script>';
}
?>
You should use PHP-PDO in order to avoid from SQL Injection attacks also it will fix insert trouble too.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$sql = "INSERT INTO users(username,
password,
email,
type) VALUES (
:username,
:password,
:email,
:type)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Are you connecting properly?
$dbuser = "";
Maybe must be "root" or other user?
Check this part :
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";

Why won't the data be stored in my database?

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested

Basic PHP-script doesn't work

I'm new to PHP and SQL but I'm trying to create a simple PHP-script that allows a user to login to a website. It doesn't work for some reason and I can't see why. Every time I try to login with the correct username & password, I get the error "Wrong Username or Password". The database-name and table-name are correct.
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);
$count 0= mysql_num_rows($result);
if($count==1){
// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass");
header("location:score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
I hope someone can find my mistake, thanks!
FYI session_register and session_is_registered are deprecated and will be removed from PHP. Also try to change your code to use mysqli or PDO. Plenty of articles explain how to do it. Finally, make sure you escape input from the user ($_POST array) because you never know what the user will send and you don't want to be prone to SQL injections. You really do not want to store passwords in clear text, so using SHA1 or MD5 is best.
Having written the above, your code becomes (you can use the $_SESSION global array directly):
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = "SELECT * FROM $tbl_name "
. "WHERE username = '$user' "
. "AND password = sha1('$pass')";
$result = mysql_query($sql);
// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{
// Register $user, $pass send the user to "score.php"
$_SESSION['user'] = $user;
// You really don't need to store the password unless you use
// it somewhere else
$_SESSION['pass'] = $pass;
header("location: ./score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if (!isset($_SESSION['user']))
{
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
A couple of things
Change this line to the one with error checking i have put below it
$result= mysql_query($sql);
$result= mysql_query($sql) or die(mysql_error());
chances are there is an sql error and you are not picking it up, so the result will always have 0 rows
Also not sure if this line is a typo or not, there shouldn't be a 0 in there
$count 0= mysql_num_rows($result);

Categories