Search code examples
phpformspost

Processing forms in PHP on the same page


So this time I decided to go with a web programming language.

I always liked the way PHP worked, so I started learning it. I've started making a login page but I just don't know whats wrong with it. No errors if I use symbols.

I don't even think the form is processed. Is this the correct way to handle a form on the same page?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<?php
session_start();
include("includes/connect.php");

if (isset($_SESSION['uid'])) {
    header('Location:member.php');
}

if (isset($_POST['submit'])) {
    $error = array();
    
    //username
    if (empty($_POST['username'])) {
        $error[] = 'You cant have no username can you';
    } else if (ctype_alnum($_POST['username'])) {
        $username = $_POST['username'];
    } else {
        $error[] = 'Username cannot contain symbols';
    }
    
    //password
    if (empty($_POST['password'])) {
        $error[] = 'YOU NEED A PASSWORD';
    } else {
        $password =  sha1(mysql_real_escape_string($_POST['password']));
    }
    
    //error
    if (empty($error)) {
        $result = mysql_query("SELECT * FROM user_info WHERE username='$username' AND password='$password'") or die(mysql_error());
        if (mysql_num_rows($result) == 0) {
            $error_message='Username or Password wrong';
        } else {
            $_SESSION['username'] = $username;
            $_SESSION['user_id'] = mysql_result($result, 0, 'user_id');
        }
    } else {
        foreach($error as $key => $values) {
            $error_message.= "$values";
        }
    }
}


?>

<html>
<head>
    <title>Login :)</title>
</head>
<body>
<div style="background-color:#A0A0A0" align="center">
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <h3>Login</h3>
    <div>
        <label for="username">Username:</label>
        <input type="text" name="username" maxlength="10"/>
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" name="password" maxlength="20"/>
    </div>
    <div>
        <input type="submit" name="submit "value="Login"/>
    </div>
</form>
<?php echo $error_message; ?>
</div>
</body
</html>

Solution

  • your body tag isn't closed you forgot >

    </body>
    

    and delete the space in the submit button's name :)