As a task my teacher has given me (highschool year 10) to create a login form using html and php as we have just started to learn PHP i have made progress and this is my first attempt. I will go into more secure options later.
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST[username];
$password = $_POST[pawd];
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['username'];
if($value == "$username")
{
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['password'];
if($value == "$password")
{
$sql=("UPDATE user_check SET user = '1' ");
$sql=("UPDATE user_check SET name = '$username' ");
header( 'Location: feed.php' ) ;
}
else
{
header( 'Location: social.php' ) ;
}
}
else
{
header( 'Location: social.php' ) ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Where it says
$sql=("UPDATE user_check SET user = '1' ");
$sql=("UPDATE user_check SET name = '$username' ");
The first one will work and update the database to 1 however the second one doesn't i have checked the name of the column changed the name of the variable $sql and $username and it still won't work is there any suggestions? Thankyou in advance :D
You first compare $_POST['username'] to the username column from the result, but then you try to update the name column in the database. My guess is that:
$sql = ("UPDATE user_check SET name = '$username' ");
should be:
$sql = ("UPDATE user_check SET username = '$username' ");
This looks strange:
$sql=("UPDATE user_check SET user = '1' ");
$sql=("UPDATE user_check SET name = '$username' ");
The second line will overwrite the value stored in the previous first one.
Try putting a
die($sql)
before the line where you call the SQL, to see if what you think you are running is what you are running.
Related
For my website I need to be able to get an ID from a database after someone logged in. I already figured out how to put the variables from the login page into a session but I cant figure out how to write a code that gets an ID from a database and turns it into a session variable.
session_start();
include( "connection.php" );
if(isset($_GET['action']) && ($_GET['action'] == "login")){
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$pass = mysqli_real_escape_string($conn, md5( $_POST['pass'] . "90qdjka*#"));
$QUERY = "SELECT * FROM users WHERE username = '$name' AND password = '$pass' AND enabled = 1";
$EXEC = mysqli_query($conn, $QUERY );
if(mysqli_num_rows($EXEC)==0){
die( 'Login niet geldig! Opnieuw inloggen' );
}else{
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
$QUERY = "UPDATE users SET lastlogin=NOW() WHERE username = '$name' AND password = '$pass'";
mysqli_query($conn, $QUERY);
}
}
?>
else{
if (mysqli_num_rows($EXEC) > 0) {
while($row = mysqli_fetch_assoc($EXEC)) {
$_SESSION['id'] = $row["id"];
}
}
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
if your query returns only one result then while loop will run only one time but if your query returns more than one record then the last record's id will be stored in your session variable
In $row["id"], id is the column name of the table, if you are selecting all columns from your table and if your users table has columns like name, username, password then you can access it using $row["name"], $row["username"], $row["password"]
I've created a below script, which is intentionally not secure, in order to learn a bit more about cyber security.
session_start();
if($_SESSION['userSession']) {
header("location: home.php");
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect("localhost", "myUsername", "myPassword", "myDatabase");
if(!$con) {
die("Error: " . mysqli_connect_error());
}
$query = "SELECT * FROM users WHERE username = '$username' && password='$password'";
$result = mysqli_query($con, $query);
$numResults = mysqli_num_rows($result);
if($numResults == 1) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['userSession'] = $row['id'];
header("location: home.php");
} else {
echo "Error Logging In";
}
mysqli_close($con);
}
As you can see, I have not escaped the user input and the password has not been hashed.
Therefore, I am presuming that this should be an easily hackable login. However, I have attempted to use the below input in both of the username and password fields, but always get the output "Error Logging In".
password' OR '1' = '1'";
How can I try to bypass/hack my login script?
If we use sql statement directly to fetch username and password field then it can be bypass with ' OR '1' = '1 pattern, because when you put ' OR '1' = '1 in username and password field that values carry forward to sql statement and in that statement ' or '1' = '1 is true for all the cases and that's a reason login can bypass.
login php with different user by classified the code using nested if method, however, it will only run the first if but not the second
$sql= mysql_query("SELECT * FROM user WHERE id= '$id' AND password= '$password'");
$sql1 = "SELECT position FROM user WHERE id ='$id' AND password = ' $password'";
if(mysql_num_rows($sql) > 0)
{
if($sql1 = "student" )
where the nested if begin
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='google.com.my'
</SCRIPT>");
}
else if($sql1 = "lecturer" )**it will not run until this if **
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully123!.')
window.location.href='www.yahoo.com'
</SCRIPT>");
}
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='login.html'
</SCRIPT>");
exit();
}
}
?>
use
$sql1 = mysql_query("SELECT position FROM user WHERE id ='$id' AND password = ' $password'");
instead of
$sql1 = "SELECT position FROM user WHERE id ='$id' AND password = '$password'";
You have to fetch the data from table using mysql_fetch_array or mysql_fetch_assoc
And if condition should be
if($something == "student" )
not
if($something = "student" )
EDIT
Try like this..and make required changes
$sql1 = mysql_query("SELECT position FROM user WHERE id ='$id' AND password = ' $password'");
if($row = mysql_fetch_array($sql1))
{
$result = $row['position'];
}
Then
if($result == "student")
{
//do something...
}
In your second sql statement, change ' $password'"; to '$password'";
You are not comparing, but assigning value to $sql1
if($sql1 = "student" )
Change to
if($sql1 == "student" )
For password safety, use password_hash function
You never run a query to return a value to $sql1. put mysql_query around your $sql1 query and it'll return what you want. Also you're not breaking out of your query to input data, you have to do mysqli_query("SELECT * FROM user WHERE id = "' . $id . '" AND password = "' $password'");
Also you should move to mysqli_query rather than mysql_query.
MySQL vs MySQLi when using PHP
I have a quick login form that i made for school the only problem is that when i try and login everything worked perfectly when i want to log into the first user (Username: hbutler Password: password) However when i try to login to my other accounts i get the page refresh which i have set it do if it is incorrect here is my code :
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['username'];
if($value == "$username")
{
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='$username'");
$row = mysqli_fetch_array($result);
$value = $row['password'];
if($value == "$password")
{
$sql=("UPDATE user_check SET user = '1', name = '$username'");
header( 'Location: feed.php' ) ;
}
else
{
header( 'Location: social.php' ) ;
}
}
else
{
header( 'Location: social.php' ) ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Which gets the form data from the previous page i do not know why this is happening and i have tryed changing the php to this :
$result = mysqli_query($con, "SELECT username FROM User_info");
$row = mysqli_fetch_array($result);
if($row == "$username")
Yet that doesnt work either any suggestions?
the problem is that, after your first query, to get the info from db, you are taking only the first row of the table,
$row = mysqli_fetch_array($result);
then comparing it with the submitted username, that's why you can't login with any other username, the solution is to add a WHERE clause to the first query,
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='".$username."'");
then compare passwords that would be easier, but still, there are better ways to do the authentication. but for your example this should do.
Modify your code as below:
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT count(*) as count FROM User_info WHERE username ='$username' and password='$password'");
while( $rows = mysqli_fetch_array($con, $result) )
{ //Check for SQL INJECTION
if( $rows['count'] == 1 )
{
//$sql=("UPDATE user_check SET user = '1', name = '$username'");
//header( 'Location: feed.php' ) ;
//Other Operations
}
else
{
header( 'Location: social.php' ) ;
}
}
mysqli_close($con);
?>
I have a page named ques.php. If the user's answer is correct he will be directed to next ques1.php. The answer posted by the user is checked by check.php and if it is correct I want to store the new URL (ques1.php) in the users account in the database.
check.php
<?php
require_once("./include/membersite_config.php");
if (!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("login.php");
exit;
}
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("simplelogin") or die(mysql_error());
$data = mysql_query("SELECT * FROM member") or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
// print $info['username'];
if ($info['username'] == $fgmembersite->UserName()) {
$fullname = $info['name'];
$username = $info['username'];
$password = $info['password'];
$email = $info['email'];
$url = $info ['url'];
break;
}
}
$answer = $_POST['answer'];
if ($answer == "correct") {
"UPDATE `simplelogin`.`member`
SET `url` = 'ques1.php'
WHERE
`member`.`name` = '$fullname'
AND `member`.`email` = '$email'
AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y'
AND `member`.`url` = '$url'";
//in place of above update query i had also used
//"UPDATE member
//SET url = 'ques1.php'
//WHERE username = '$username'"
Header("Location:ques1.php");
} else {
Header("Location: ques.php");
}
?>
function UserName() {
return isset($_SESSION['user_name'])?$_SESSION['user_name']:'';
}
login.php
<?php
require_once("./include/membersite_config.php");
if (isset($_POST['submitted'])) {
if ($fgmembersite->Login()) {
//$fgmembersite->RedirectToURL("login-home.php");
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("simplelogin") or die(mysql_error());
$data = mysql_query("SELECT * FROM member") or die(mysql_error());
while ($info = mysql_fetch_array( $data )) {
if ($info['username']==($fgmembersite->SafeDisplay('username'))) {
$url = $info['url'];
break;
}
}
$fgmembersite->RedirectToURL("$url");
}
}
?>
In login.php I am retrieving the URL from the database and redirecting the user - by default URLfor the user is ques.php.
Why is my query not updating the url in my database?
"UPDATE `simplelogin`.`member` SET `url` = 'ques1.php' WHERE
`member`.`name` ='$fullname'
AND `member`.`email` = '$email' AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y' AND `member`.`url` = '$url'" ;
Doesnt appear to be running as a query, you haven't placed it within the mysql_query() function so it has no idea what you are trying to do with that statement.
Try this instead:
mysql_query(
"UPDATE `simplelogin`.`member` SET `url` = 'ques1.php' WHERE
`member`.`name` ='$fullname'
AND `member`.`email` = '$email' AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y' AND `member`.`url` = '$url'");
Updated due to comments below:
Try this, it's been rewritten and simplified and should work, if not please port of you get the error message or not
mysql_query("
UPDATE
member
SET
url = 'ques1.php'
WHERE
name = '$fullname'
AND
email = '$email'
AND
username = '$username'
AND
password = '$password'
AND
confirmcode = 'y'
AND
url = '$url'
") or die('Unable to update members URL: ' . mysql_error());
As it is you are looping a set of database results and comparing against a value that you already have, just to get the value that you already have. At best this verifies that the user exists in the database, at worst it does nothing at all.
Really you need to be using the Primary Key of your database table for the UPDATE. Best practice dictates that this should be an auto-incrementing integer, which has no relevance to the data other than to identify the row. When you initialise the $fgmembersite object this value should be stored in it, so it can easily be used in any database query which requires a reference to the user. At worst, a unique index should be present on the username column of the table.
You can can remove the SELECT query completely - you already have the username, so you can just use this directly in the UPDATE:
check.php:
<?php
require_once("./include/membersite_config.php");
// Redirect to login page if not already authenticated
if (!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("login.php");
exit;
}
// Define DB connection info in variables for readability/maintainability
$dbHost = 'localhost';
$dbUser = 'root'; // NEVER use root for a live website!
$dbPass = ''; // A blank root password? Really?
$dbName = 'simplelogin';
// Connect to database - NEVER show the result of mysql_error() in a live site!
mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
if ($_POST['answer'] == 'correct')
// Update the database with the new URL
$query = "
UPDATE `member`
SET `url` = 'ques1.php'
WHERE `username` = '".mysql_real_escape_string($fgmembersite->UserName())."'
";
mysql_query($query) or die(mysql_error());
// This line should help you debug the query. REMOVE IT before putting this script on a live site!
if (!mysql_affected_rows()) die("No rows were affected by the query.\nQuery: $query\nError: ".mysql_error());
// Redirect to ques1.php
// Note that a header redirect should provide a FULL url, not just a relative path.
header("Location:ques1.php");
} else {
// Redirect to ques.php
header("Location: ques.php");
}
?>
login.php
<?php
require_once("./include/membersite_config.php");
if (isset($_POST['submitted']) && $fgmembersite->Login()) {
// Define DB connection info in variables for readability/maintainability
$dbHost = 'localhost';
$dbUser = 'root'; // NEVER use root for a live website!
$dbPass = ''; // A blank root password? Really?
$dbName = 'simplelogin';
// Connect to database - NEVER show the result of mysql_error() in a live site!
mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
// Fetch the URL from the database
$query = "
SELECT `url`
FROM `member`
WHERE `username` = '".mysql_real_escape_string($fgmembersite->UserName())."'
";
$result = mysql_query($query) or die(mysql_error());
if (!mysql_num_rows($result)) die('Invalid user name');
$info = mysql_fetch_assoc($result);
$url = $info['url'];
// Redirect to URL
// Add some error checking to verify that $url actually contains something valid!
$fgmembersite->RedirectToURL($url);
} else {
// What happens if the condition fails?
}
?>
execute the query dude.... use mysql_query("$your_update query");