Vote count:
0
recently I have come accross that my login form code isn't very safe and prone to SQL Injection. I would like to learn more on how to improve this. For instance, this code:
logphp.php
<?php
ob_start();
session_start();
include_once 'connection.php';
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM login WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and print "true"
echo "true";
$_SESSION['username'] = $myusername;
$_SESSION['password'] = $mypassword;
}
else {
//return the error message
echo "Wrong Username or Password";
}
ob_end_flush();
?>
logout.php
<?php
session_start();
session_destroy();
header("location:login.php");
exit();
?>
i have this on every page
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
Finally ajax
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#myusername").val();
var password = $("#mypassword").val();
if((username == "") || (password == "")) {
$("#message").html("Please enter a username and a password");
}
else {
$.ajax({
type: "POST",
url: "logphp.php",
data: "myusername="+username+"&mypassword="+password,
success: function(html){
if(html=='true') {
window.location="ind.php";
}
else {
$("#message").html(html);
}
},
beforeSend:function()
{
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>")
}
});
}
return false;
});
});
Questions:
- How could I improve it? I have heard that it's better to store userID rather than usernames in sessions but whenever I try to use userID rather than username it doesn't work.
- How can I create user access to either Admin side or User side in PHP.In the table I have "access" fields which has admin and the rest of user. I want the admin to go to a different page and the user to go to a different page.
For some reason I feel like I shoud know to create a basic secure login form but seem to be struggling.
asked 34 secs ago
Questions about Login form in PHP MYSQL Ajax
Aucun commentaire:
Enregistrer un commentaire