1

I have been trying to get validation messages from my login.php to display on the page with the form, where am I going wrong? I did try JavaScript at one point to display the information with no luck, it keeps displaying as seen in the image below.

I know it could be added to the same page for the result I want but I'm trying to do it as a clean page, with no jQuery, some vanilla JavaScript at very most. The aim is to have the validation messages above the form, at first I was thinking spans but I'm not sure where to look for tutorials on how to output results from another file while staying on the same page.

http://snag.gy/SI9lq.jpg

      <table border ='0'>
                <form action="login.php"  method="POST">
                    <tr><td>Username:</td> <td><input type="text" name="username" required></td></tr>
                    <tr><td>Password:</td> <td><input type="password" name="password" required></td><tr>
                    <tr><td><input button id="myBtn" type="submit" value="Log in"><td></tr>
                    <tr><td><a href='register.php'>Register</a></td></tr>
            </table> 




     <?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$errors = array();


if ($username&&$password)
{

$connect = mysql_connect("localhost","root","") or die ("Could not connect");
mysql_select_db ("login") or die ("Could not find database");

$query = mysql_query("SELECT * FROM users WHERE username ='$username'");

$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
    while ($row =mysql_fetch_assoc($query))
    {
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    }

    if ($username==$dbusername&&$password==$dbpassword)
    {
        echo header( 'Location: member.php' ) ;
        $_SESSION['username']=$dbusername;
    }
    else 
        echo"
         <script type=\"text/javascript\">
        window.onload = function latestNews(){
      var newPara = document.createElement('p');
      var add_news = document.createTextNode('Incorrect password');
      newPara.appendChild(add_news);
      var getSecond = document.getElementById('footer');
      document.body.insertBefore(newPara, getSecond);
    };
         </script>
    ";
}
else
    die("That user dosen't exist");

}

else
    die("Please enter a username and a password");
?>

EDIT

I attempted to add JavaScript although it had the same effect.

4
  • 2
    "how to output results from another file while staying on the same page" - Use Ajax. Commented Dec 6, 2014 at 18:04
  • If "on the same page" means without reloading fully a page, javascript is needed. If it just means without changing the URL, javascript is not needed. @Jon Snow : Could you tell us a bit more about your needs ? Commented Dec 6, 2014 at 18:13
  • @Jon Snow : By the way, you should definitely have a look at https://www.owasp.org/index.php/Top_10_2013-Top_10 and at https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet. Your code is quite dangerous, especially the $username, provided by visitor's client, in SQL request! Commented Dec 6, 2014 at 18:23
  • Firstly thanks for the links, I have book marked them to read, this code won't be for the public it's more of a learning task, I'm aiming for this result: snag.gy/Bcm4O.jpg , however with the PHP in say for example login.php and the form in index.php Commented Dec 6, 2014 at 18:34

4 Answers 4

3

To display a simple error message you simply echo it above the form. See if this works

<?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$errors   = array();
$msg      = ""; //define an error msg variable


if (isset($_POST['username'], $_POST['password'])) {

    $connect = mysql_connect("localhost", "root", "") or die("Could not connect");
    mysql_select_db("login") or die("Could not find database");

    $query = mysql_query("SELECT * FROM users WHERE username ='$username'");

    $numrows = mysql_num_rows($query);
    if ($numrows != 0) {
        while ($row = mysql_fetch_assoc($query)) {
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        }

        if ($username == $dbusername && $password == $dbpassword) {
            echo header('Location: member.php');
            $_SESSION['username'] = $dbusername;
            $_SESSION['userid']   = $userid;
        } else
            $msg = "Incorrect password";
    } else
        $msg = "That user dosen't exist";

}

else
    $msg = "Please enter a username and a password";

?>


<div class='errorMsg'><?php echo $msg; ?></div>
  <form action="login.php" method="post"></form>
  <table border='0'>
    <tr>
      <td>Username:</td>
      <td><input name="username" required="" type="text"></td>
    </tr>

    <tr>
      <td>Password:</td>
      <td><input name="password" required="" type="password"></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td><input id="myBtn" type="submit" value="Log in"></td>
      <td></td>
    </tr>
    <tr>
      <td>
        <a href='register.php'>Register</a>
      </td>
    </tr>
  </table>
  </form>
Sign up to request clarification or add additional context in comments.

1 Comment

The solution seems to be here, and it is very similar to the question code. However a comment should be added : // WARNING : This code is as dangerous as the question code. SQL Injections could be done.
1

what about if you do this

<?php
$connect = mysql_connect("localhost","root","") or die ("Could not connect");
mysql_select_db ("login") or die ("Could not find database");

session_start();
function output_errors($errors){
return '<ul class="a"><li><strong>'.implode('</li><li>', $errors) .'</strong></li></ul>';
}

$errors = array();

if(empty($_POST) === false) {
$required_fields = array('username', 'password');
foreach ($_POST as $key=>$value) {
if(empty($value) && in_array($key, $required_fields) === true){
$errors[] = 'user name and password is empty !';
break 1;
}
}
$username = $_POST['username'];
$password = $_POST['password'];
if(strlen($_POST['password']) < 5){
$errors[] = 'Your password must be at least 5 Characters.';
}
if ($username&&$password)
{

$query = mysql_query("SELECT * FROM users WHERE username ='$username'");

$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
    while ($row =mysql_fetch_assoc($query))
    {
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    }

    if ($dbusername&&$password != $dbpassword) {
     $errors[] = "password wrong";  
    }
}
}
}
if(empty($_POST) === false && empty($errors) === true && $username==$dbusername&&$password==$dbpassword){
echo header( 'Location: member.php' ) ;
$_SESSION['username']=$dbusername;
exit();
}else if(empty($errors) === false){
echo output_errors($errors);
}
?>

              <table border ='0'>
                        <form action="login.php"  method="POST">
                            <tr><td>Username:</td> <td><input type="text" name="username" ></td></tr>
                            <tr><td>Password:</td> <td><input type="password" name="password" ></td><tr>
                            <tr><td><input button id="myBtn" type="submit" value="Log in"><td></tr>
                            <tr><td><a href='register.php'>Register</a></td></tr>
                    </table> 

7 Comments

I did try, bounced me off to a blank page
sure because you have to put your php code over the form also your blank page causes of exit() you can remove it
and the answer of Aditya is the best solution for you .
let me guess if i understand you correctly , do you want to show the errors in the same page not in blank page or even destroyed page ?
also the required input are not necessary do it like that type="text" name="username"
|
1

Write a new PHP program, perhaps called checker.php. It is the job of checker.php to check for errors and present a "success" page if none are found. However, if checker.php finds an error, it sets a PHP variable, $error = TRUE; (You could use an array of you want to be able to report more than one error type; just have each element of the array be a code/abbreviation for the error type.) If there is an error, checker.php issues include 'login.php' which will redisplay your login page.

Here's the trick: have login.php check for $error like this: if isset($error) { ... and if so, use PHP's echo to display your error messages. You can carry forward things like the user ID and password in a $error array if you like. (But heed the cautions about security in the comments.)

If $error is not set, your login page is being displayed for the first time. Display it without error messages.

Here is a sort-of minimalist login.php:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Login Form</title>
<style type="text/css">
p.error {color: red;}
</style>
</head>
<body>
<?php
   if (isset($error)) {  // same message for user ID or password for security
      echo '<p class="error">Error in user ID or password; please re-enter.</p>';
   }
?>
<form method="post" action="checker.php">
<label>User ID: <input type="text" name="userid" /></label><br />
<label>Password: <input type="text" name="password" /></label><br />
User ID: <input type="submit" value="Login" /><br />
</form>
</body>
</html>

And here is checker.php:

<?php
    $userid=(isset($_POST['userid']) ? $_POST['userid'] : FALSE);
    $password=(isset($_POST['password']) ? $_POST['password'] : FALSE);
    if ($userid !== 'jsnow') $error[] = 'userid';
    if ($password !== 'Ygritte') $error[] = 'password';
    if (isset($error)) {
        include 'login.php';
        exit;
    }
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Success</title>
</head>
<body>
<h1>Success!</h1>
<p>You're logged in.  What do you want to do?</p>
</body>
</html>

It is possible to include the code from checker.php` in the login.php page, but it's easier to see what's going on if you write two separate pages. Try that before you try combining them.

6 Comments

I tried include "checker.php"; <?php if (isset($errors)) { echo $errors; }; ?> If I understood correctly, but I was still getting the same white page.
Make the action=' attribute on your login page be checker.php and then have checker include login.php if there's an error, otherwise display the "success" message.
I'm really confused, that brought me back in full circle, the validation message is back on a separate white page again.
Can you put your revised code somewhere that we can look at it? (One way is to edit your answer, but others have replied based on what's already there, so maybe another approach)
I've revised my answer to include a skeleton of the code I had in mind.
|
0

Well it's not excalty what I wanted but I forced myself to learn Ajax login, it's not the best it the world, well it's my first ajax login but for anyone who is interested in the answer:

Save as login:
    <?php session_start(); $username=$ _POST[ 'username']; $password=$ _POST[ 'password']; $errors=a rray(); if ($username&&$password) { $connect=m ysql_connect( "localhost", "root", "") or die ( "Could not connect"); mysql_select_db ( "login") or die ( "Could not find database"); $query=m ysql_query( "SELECT * FROM users WHERE username ='$username'"); $numrows=m ysql_num_rows($query); if ($numrows !=0) { while ($row=mysql_fetch_assoc($query)) { $dbusername=$ row[ 'username']; $dbpassword=$ row[ 'password']; } if ($username==$dbusername&&$password==$dbpassword) { echo header( 'Location: member.php' ) ; $_SESSION[ 'username']=$dbusername; } else echo "Incorrect password"; } else die( "That user dosen't exist"); } else die( "Please enter a username and a password"); ?>

Save as scripts.js:


    function createXMLHttpRequestObject() 
    {
      var ajaxObject = false;
      if (window.XMLHttpRequest) 
      {
        ajaxObject = new XMLHttpRequest();
      } 
      else if (window.ActiveXObject) 
      {
            try 
            {
                ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
         } 
    catch(e) 
             {
                try 
                    {
                    ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
                } 
    catch(e) 
                    {
                        ajaxObject = false;
                 }
         }
      }
      return ajaxObject;
    }

    function grabFile(file) 
    {
      var isAjax = createXMLHttpRequestObject();
      if (isAjax) 
        {
        isAjax.onreadystatechange = function() 
          {
          getCurrentState(isAjax);
          };
        isAjax.open("GET", file, true);
        isAjax.send(null);
      }
    }

    function getCurrentState(thisFile) 
    {
      if (thisFile.readyState == 4) 
      {
        if (thisFile.status == 200 || thisFile.status == 304) 
        {
          document.getElementById('myBtn').innerHTML = 
          thisFile.responseText;
        }
      }
    }


    function ajax_post(){
        // Create our XMLHttpRequest object
        var hr = new XMLHttpRequest();
        // Create some variables we need to send to our PHP file
        var url = "login.php";
        var un = document.getElementById("username").value;
        var pw = document.getElementById("password").value;
        var vars = "username="+un+"&password="+pw;
        hr.open("POST", url, true);
        // Set content type header information for sending url encoded variables in the request
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // Access the onreadystatechange event for the XMLHttpRequest object
        hr.onreadystatechange = function() {
            if(hr.readyState == 4 && hr.status == 200) {
                var return_data = hr.responseText;
                document.getElementById("status").innerHTML = return_data;
            }
        }
        // Send the data to PHP now... and wait for response to update the status div
        hr.send(vars); // Actually execute the request
        document.getElementById("status").innerHTML = "processing...";
    }

I didn't include the database it was starting to become a wall of text. Thank you to everyone for the advice and suggestions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.