Friday, October 4, 2019

php - $_POST not working. "Notice: Undefined index: username..."











So, I am currently learning PHP and was reading on a book about the md5 function for passwords, so I decided to give it a try and see how it goes. I also decided to use the POST method rather than the GET, since I saw people saying that it is safer and doesn't let the variables appearing on the URL.



For my testing project I made a very simple form, which follows:
























Username:
Password:








The problem is that when I enter the values on BOTH fields and click "Login" I get the following output on the other PHP file.



Notice: Undefined index: username in C:\xampp\htdocs\md5\home\dologin\index.php on line 11
Username non existent



Here follows the code for the "/dologin/index.php" file











mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
$result = mysql_query($query);
$row = mysql_num_rows($result);
if(isset($row)){
$password = (mysql_result($result,$row - 1));
$enteredpassword = md5("w@#$@#".$_GET['password']."^#3f%#^");
if($password == $enteredpassword){
if(!isset($_COOKIE['PHPSESSID'])){

session_start();
}
$_SERVER['LOGIN_STATUS'] = true;
} else {
die("Access denied");
}
} else {
die("Username non existent");
}


?>




Any help at all on my issue is very much appreciated, thank you for reading.


Answer



undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.



You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.




If I was having a similar error, I'd do something like this:



$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;


If username didn't turn up, that'd mean I was screwing up somewhere. You can also,



var_dump($_POST);



To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...