Doruk Ayar Doruk Ayar - 1 month ago 6
PHP Question

XML PHP Login Error

I'm trying to make a login form with XML and PHP but always I get an error. My HTML file:



<form action="login.php" method="post">
<input type="text" name="username" />
<br>
<br>
<input type="password" name="pass" />
<br>
<br>
<input type="submit" value="Login!" />
</form>





And my PHP file:

<?php

$xml = simplexml_load_file('users.xml');
$usr = $_POST['username'];
$pass = $_POST['pass'];
if(empty($usr)) {
die('Please enter an username!');
} elseif(empty($pass)) {
die('Please enter a password!');
}
$l_usr = null;
$pass_e = md5($pass);
foreach($xml->user->username as $username) {
if($username == $usr) {
$l_usr = $username;
}
}
if(empty($l_usr)) {
die('User Not Found!');
}
if(!$xml->user->$l_usr->password == $pass_e) {
die('Wrong Password!!');
}

echo 'Hello, '.$l_usr;


Is my codes. It's not working. And users.xml file is like this:

<users>
<user>
<username>doruk.ayar</username>
<password>96b9c62c86f35c209c5b8c302ba34175</password>
</user>
<user>
<username>mina.alpturer</username>
<password>32250170a0dca92d53ec9624f336ca24</password>
</user>
<user>
<username>efe.gormus</username>
<password>32250170a0dca92d53ec9624f336ca24</password>
</user>
</users>


It's not working. When I write the correct username and correct password, it says "User Not Found!". Can someone help me?

NOTE: The passes:

doruk.ayar: 123pass
efe.gormus: pass123
mina.alpturer: pass123

Answer

I've debugged your code and the user is found correctly but I've noticed another error in below part of your code

if(!$xml->user->$l_usr->password == $pass_e)

This return always NULL and operator "!" is useless here

$xml->user->$l_usr->password

I've fixed It writing more efficient and correct code

<?php
$xml = simplexml_load_file('users.xml');
$usr = $_POST['username'];
$pass = $_POST['pass'];
if(empty($usr)) {
  die('Please enter an username!');
} elseif(empty($pass)) {
  die('Please enter a password!');
}
$pass_e = md5($_POST['pass']);
$valid=false;
foreach($xml->user as $userNode)
{
  if($userNode->username==$usr && $userNode->password==$pass_e)
 {
   $valid=true;
   break;
 }
}

if($valid==false)
{
  die('Wrong password or username');
}

echo 'Hello, '.$usr;