Sven.K Sven.K - 6 months ago 7
PHP Question

PHP: variables not working after running "if" command

Recenty i was planning on creating a database processor and after processing the login info the varables that contained the data couldn't be found (dissapeared) and whatever i would try to run in the "if" that verified the login info after the popup i created in javascript wouldn't appear on the screen.

The login info is sent from a login screen, and this is the code that sends the data:

Login

<form action="login1.php" method="post">
Username:<br><input type="text" name="uname">
<br>
Password:<br><input type="Password" name="pass">
<br>
<input type="submit" value="Login" name="submit">
</form>

</fieldset>
<form action="MainScreen.html" method='get'>
<button type='Submit'>Inapoi la pagina principala</button>

</form>


This is the screen that proceses the login info

<?php
require('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
global $z;
$z=substr($username, 0, -1);
$q=$z;
///mysql_query($z);
if (!$_POST['uname'] or !$_POST['pass']){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Nu ati completat toate campurile necesare.\nVa rugam incercati din nou.')
window.location.href='login.php'
</SCRIPT>");
}

$sql= mysql_query("SELECT * FROM `xii f` WHERE `IdPar` = '$username' AND `Password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo$z;
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Bine ati venit domnule/doamna ".$z."')
window.location.href='login1.php'
</SCRIPT>");
/* Here i tried to run a table, but it doesn't seem to work
$sq= mysql_query("SELECT * FROM `absente s1` WHERE `Nume` ='$z'");
echo'
<table border="2" style= "background-color: white; color: black; margin: 3 auto; font-size:95%;" >
<thead>
<tr>
<th>Absenta</th>
<th>Materie</th>
<th>Motivat</th>
</tr>
</thead>
<tbody>';

while( $row = mysql_fetch_assoc($sq) )
echo "<tr>
<td>{$row['Absenta']}</td>
<td>{$row['Materie']}</td>
<td>{$row['Motivat']}</td>
</tr>";

echo'
</tbody>
</table>';

*/
}
else{
$sql= mysql_query("SELECT * FROM `Profesori` WHERE `IdProf` = '$username' AND `Password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
$k=mysql_query("SELECT * FROM `Profesori` WHERE `sex`='M' AND `IdProf` = '$username' AND `Password` = '$password'");
if(mysql_num_rows($k) > 0){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Bine ati venit domnule ".$z."')
window.location.href='login1.php'
</SCRIPT>");
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Bine ati venit doamna ".$z."')
window.location.href='login1.php'
</SCRIPT>");
}
}
else{
$sql= mysql_query("SELECT * FROM `Diriginte` WHERE `Id` = '$username' AND `Password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Bine ati venit domnule ".$z."')
window.location.href='login1.php'
</SCRIPT>");
}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Nume de utilizator sau parola gresite. Va rugam reintroduceti.')
window.location.href='login.php'
</SCRIPT>");
}
}
}
}
?>


The sql_connect.php file is used to esablish the connection to the serv and the database
I must mention that the code is written in a HTML formatted file in the division altrough i think it doesn't affect the php script. This is the code for the page formatting:

<style>

header {
background-color:white;
color:white;
height:5%;
width:80%;
float:left;
text-align:center;
}

details {
background-color:#B0B0B0;
color:white;
height:15%;
width:80%;
font-size:180%;
font-family: "Magneto";
float:left;
text-align:center;

}
nav {
line-height:30px;
background-color:white;
height:100%;
width:10%;
float:left;

}

section {
background-color:#F0F0F0 ;
width:20%;
height:60%;
text-align:center;
float:left;
}
aside {
background-color:#F0F0F0;
width:40%;
height:60%;
font-family: "High Tower Text";
text-align:center;
float:left;
}
summary{
background-color:#F0F0F0;
width:20%;
height:60%;
text-align:left;
float:left;
}
article {
background-color:#B0B0B0;
color:white;
text-align:center;
font-family:'Copperplate Gothic Bold';
height:15%;
width:80%;
float:left;
}
background-color:red;
</style>


td;lr Variables are dissparearing after running the "if" command.

EDIT: Solved issue. Turns out it was due to the
window.location.href='login1.php'
command that reloaded the page

Answer

Taking into account most of the comments I made on the question, I created a functional replica of your application, making some of the much needed corrections.

login.php

<form name="loginForm" action="login-validation.php" method="post" onsubmit="return validate()">
    Username:&emsp;<input type="text" name="uname"><br/>
    Password:&emsp;<input type="Password" name="pass"><br/>
    <input type="submit" value="Login" name="submit">
</form>

<a href="MainScreen.html">Inapoi la pagina principala</a>

<script>
function validate() {
    var uname = document.forms["loginForm"]["uname"].value;
    var pass = document.forms["loginForm"]["pass"].value;
    if ((uname == null || uname == "") || (pass == null || pass == "")) {
        alert("Please fill out all the fields.");
        return false;
    }
}
</script>

login-validation.php

<?php
if (isset($_POST['submit'])){
    $con = new mysqli("localhost","root","","stackoverflow");

    if (mysqli_connect_errno()) {
        printf("Database Error: %s\n", mysqli_connect_error());
        exit("<br/><a href='login.php'>Try again</a>");
    }

    $username = $con->real_escape_string($_POST['uname']);
    $password = $_POST['pass'];

    // Fetch user by username & close the connection to the database
    $result = $con->query("SELECT * FROM `users` WHERE `username` = '$username'");
    $con->close();

    // Retrieve data
    $row = $result->fetch_row();

    // Check if there's a match
    if(!empty($row)) {

        // Validate password
        if(strcmp($password, $row[2]) == 0) {

            // Save Result in Session for future uses
            $_SESSION['uid'] = $row[0]; // users.id
            $_SESSION['username'] = $row[1]; // users.username
            $_SESSION['password'] = $row[2]; // users.password
            $_SESSION['role'] = $row[3]; // users.role

            // Exit sending a message to the now logged user
            exit("Bine ati venit domnule/doamna ".$row[1]);
        } else {

            // Exit if password doesn't match, provide link for trying again
            exit("Incorrect password<br/><a href='login.php'>Try again</a>");
        }
    }

    // If there was no match in the query, throw message and exit
    exit("Invalid data<br/><a href='login.php'>Try again</a>");
}
// Create a link to the login page and exit if there was no POST data
exit("<a href='login.php'>Login</a>");

The database structure for the table users:

CREATE TABLE IF NOT EXISTS `users` (
    `id` int(11) NOT NULL,
    `username` varchar(512) NOT NULL,
    `password` varchar(512) NOT NULL,
    `role` tinyint(4) NOT NULL DEFAULT '1'
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `password`, `role`) VALUES
(1, 'student', 'student', 0),
(2, 'teacher', 'teacher', 1),
(3, 'other', 'other', 0);

ALTER TABLE `users`
    ADD PRIMARY KEY (`id`),
    ADD UNIQUE KEY `username` (`username`);


ALTER TABLE `users`
    MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

Some of the still missing proper adjustments:

  • Encryption for the stored passwords
  • Control of access to the login page (redirect logged users)
  • Control of access to the login validation page
  • Better management of what happens to logged users
  • Better management (more user friendly) of what happens when login fails
Comments