Jump to content

Recommended Posts

create these pages:

1) home.php

2) register.php

3) login.php

4) doLogin.php

5) logout.php

6)db.php

-----------

step 1) create a new database,name the database as database, name the table as user, 3 fields, id INT(11) AUTO INCREMENT, username VARCHAR (20), password VARCHAR(20)

step 2) create a project in the program you are using.

step 3) copy the codes to the following php files you created.

step 4) make sure your project exists in xampp/htdocs folder.

step 5) on the xampp panel, on service (apache / mysql)

step 6) go to the site and check if its working. the end.

 

--------------------------------------

db.php

<?php

function connect() {
    mysql_connect("localhost","root","");
    mysql_select_db("database");
}

function protect($string) {
    return mysql_real_escape_string(strip_tags(addslashes($string)));
}

        $HOST = "localhost";
        $USERNAME = "root";
        $PASSWORD = "";
        $DB = "database";
        
        $link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);
?>

register.php

<?php 
if (isset ($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] != $_SERVER['PHP_SELF']) {
	$_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
}

// Security measure, to avoid XSS exploit.
if (!empty ($_SERVER['PATH_INFO']) && strrpos ($_SERVER['PHP_SELF'], $_SERVER['PATH_INFO'])) {
	$_SERVER['PHP_SELF'] = substr ($_SERVER['PHP_SELF'], 0, -(strlen ($_SERVER['PATH_INFO'])));
}
?>
<?php
include("db.php");
connect();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Register Page</title>
    </head>
    <body bgcolor ="lightblue">
        <a href ="home.php">Home</a><br><br>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username:* <input type="text" name="username" placeholder="Username 5-15 Char."/><br />
Password:* <input type="password" name="password" placeholder="Password 6-15 Char."/><br />
<input type="submit" name="register" value="Register"/>
</form>
        
        <?php
        
        if(isset($_POST['register'])){
    $username = protect($_POST['username']);
    $password = protect($_POST['password']);
    
    if($username == "" || $password == ""){
        echo "Please fill in all fields!";
    }elseif(strlen($username) < 4) {
        echo "Username must be greater than 4 characters!";
    }elseif(strlen($username) > 15){
        echo "Username must be less than 15 characters!";
    }
    
    elseif (strlen($password) < 6) {
        echo "Password must be greater than 6 characters!";
    }elseif (strlen($password) > 15) {
        echo "Password must be lesser than 15 characters";
    }
    else{
        $register1 = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'") or die(mysql_error());
        if(mysql_num_rows($register1) > 0){
            echo "That username is already in use!";
        }
        else{
            $ins = mysql_query("INSERT INTO user (username, password)
         Values('$username','$password')") or die(mysql_error());
            echo "You have registered succesfully!";
        }
        }
        }
        ?>
        <br><br>Already a member? <br>Click here to <a href="login.php" /> Login!</a>
    </body>
</html>

login.php

<?php
include 'functions.php';
// check if user is authenticated
session_start();
if (isset($_SESSION['user_id'])) {
echo "You are already logged in.<br/>.";
     }

     else
     {
      
     }
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page</title>
    </head>
    <body bgcolor ="lightblue">
         <form method="post" action="doLogin.php">
             <table>
                    <tr>
                        <td><label for="username">Username:</label></td>
                        <td><input type="text" id="username" name="username" required/></td>
                    </tr>
                    <tr>
                        <td><label for="password">Password:</label></td>
                        <td><input type="password" id="password" name="password" required/></td>
                    </tr>
                    
             </table>
             <input type="submit" value="Login" name="submit"/>
        </form> 
        
    </body>
</html>

doLogin.php

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    if (isset($_POST['username'])) {
        //retrieve form data
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);


        //connect to database
        $HOST = 'localhost';
        $USERNAME = 'root';
        $PASSWORD = '';
        $DB = 'database';

        $link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);

        //match the username and password entered with database record
        $query = ("SELECT * FROM `user` WHERE `username`='$username' AND `password`='$password'");
        $result = mysqli_query($link, $query) or die(mysqli_error($link));

        //if record is found, store id and username into session
        if (mysqli_num_rows($result) >0) {
            $row = mysqli_fetch_array($result);
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['username'] = $row['username'];

            $msg = '<p><i>Hello, ' . $row['username'] . '!<br />';
            $msg .= 'You are logged in.<br /><a href="home.php">Home</a></p>';
        } else { //record not found
            $msg = '<p class="error">Sorry, you must enter a valid username and password to log in.<a href="login.php"> Back</a></p>';
            
        }
    }
} else {
    $msg = 'You are already logged in.<br /><a href="home.php">Home</a></p>';
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css" />
        <title>Login page</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

    <header><b></b></header>

</head>
<body bgcolor ="lightblue">

    <?php
    echo $msg;
    ?>
    <?php
    header("refresh:4;url=home.php");
    ?>

</body>
</html>

home.php

<?php 
if (isset ($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] != $_SERVER['PHP_SELF']) {
	$_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
}

// Security measure, to avoid XSS exploit.
if (!empty ($_SERVER['PATH_INFO']) && strrpos ($_SERVER['PHP_SELF'], $_SERVER['PATH_INFO'])) {
	$_SERVER['PHP_SELF'] = substr ($_SERVER['PHP_SELF'], 0, -(strlen ($_SERVER['PATH_INFO'])));
}
?>

<?php
session_start();
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DB = 'database';

$link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);
if (!$link) {
    die(mysqli_error($link));
}

?>

<!DOCTYPE html>
<html>
    
    <head>
    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>MY FIRST PROGRAM</title>
    </head> 
    <body bgcolor ="lightblue">
        <div id="container">
                   <?php
        if (isset($_SESSION['user_id'])) {
            if ($_SESSION['role'] == 'ban')
{
    echo '<meta http-equiv="refresh" content="0; url=ban.php " />';
    die();
}
            elseif ($_SESSION['role'] == 'member'){
           ?>
            <header><b>MY FIRST PROGRAM</b>
            <nav>
           <a href="home.php">Home | </a>
           <a href ="accountPanel.php">Account Panel | </a>
           <a href="logout.php">Logout</a><br />
            </nav>
            </header>
        
            <?php 
            $link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);

        //match the username and password entered with database record
        $query = ("SELECT id,username FROM `user` WHERE id='".$_SESSION['user_id']."'");
        $result = mysqli_query($link, $query) or die(mysqli_error($link));
            $row = mysqli_fetch_array($result);
            $_SESSION['user_id']= $row['id'];
            $_SESSION['username'] = $row['username'];
            

            echo '<p><i>Welcome, '. $_SESSION['username'];?>
        
            <?php
                   } else{ ?>
            <header><b>MY FIRST PROGRAM</b>
            <nav> <a href="home.php">Home | </a>
           <a href ="adminPanel.php">Admin Panel | </a>
           <a href="logout.php">Logout</a><br />
            </nav>
            </header>
                <?php 
                        $query = ("SELECT id,username FROM `user` WHERE id='".$_SESSION['user_id']."'");
        $result = mysqli_query($link, $query) or die(mysqli_error($link));
            $row = mysqli_fetch_array($result);
            $_SESSION['user_id']= $row['id'];
            $_SESSION['username'] = $row['username'];
                echo '<p><i>Welcome, '. $_SESSION['username'];?><br>
          
        <?php }} else {
            ?>
            <header><b>MY FIRST PROGRAM</b>
            <nav>
           <a href="home.php">Home</a>
           <a href ="register.php">Register</a>
           <a href="login.php">Login</a><br />
           </nav>
            </header>
             
            <?php
        }
        ?>
            <br>
        </div>
    </body>
</html>

logout.php

<?php

session_start();
session_destroy();
header("Location: home.php");

?>

----

Just copy and paste this.

If your variables in the database is correct like what I've said, it should be fine.

Anyway, the navigation bar is only for show, just ignore it.

Edited by KaiSheng

@KaiSheng, the point of programming help is to actually troubleshoot and help with problems in the OP's code. posting 'fixed' code that's no better then the OP's code doesn't help because there's no learning going on, just copy/pasting. you need to actually post things that help the OP find what the problem is in his code.

 

the last code you posted above is a hack-up of calling database functions without first having a database connection, double-escaping data (and possibly triple if php's magic_quotes is on) mixing mysql_ and mysqli_ functions, having session_start() statements after outputting characters on the page, coding database connection information in multiple place, despite having an included file for that purpose.... and many more problems.

@SpartanTacoDuckie, i recommend that you go back to your original code and find what is wrong in it and fix it.

 

the most immediate problem with your original code that prevented it from working is your form's submit button does not have a name='submit' attribute and the if (isset($_POST['submit']) ) { statement in the php code was false.

Yeah, I fixed the other problem I had. with the variables. I was just being stupid and tired. Still didn't work, though. I'll try fixing the submit button.

 

Edit 1: I added the name="submit" attribute, but I don't see what's wrong with if (isset($_POST['submit']) ) {  ....

 

Mind explaining?

 

Edit 2: It's now outputting the message. Thanks for you people's help. But, what in the above code (^^^) is wrong? It SEEMS fine...

Edited by SpartanTacoDuckie

Another problem, though...

 

It outputs the error whenever all the fields haven't been filled in, but it's not outputting the message for a successful username and password... instead, it outputs the error...

 

Is there possibly an error with this code?:

if (isset($_POST['submit']) ) {

//get the form data

$myusername = ($_POST['username']);

$mypassword = ($_POST['password']);



//check if all fields are filled in

if ( (!$myusername == "") || (!$mypassword == "") ) {

echo "Please fill in all fields";

exit;

}


//check the form in database

$sql = "SELECT * FROM users WHERE username = '$myusername' AND password = '$mypassword'";

$result = mysql_query($sql);

$account = mysql_num_rows($result);

//check if user exists

if ($account == 1) {

$_SESSION["username"] = $myusername;

$_SESSION["password"] = $mypassword;

$_SESSION["userrecord"] = mysql_fetch_assoc($result);

echo "You have been logged in successfully. Please click <a href=account.php>here</a> to continue.";

}

??

Edited by SpartanTacoDuckie

Because i told you from the start,

do not put exclamation marks on the condition

if ( (!$myusername == "") || (!$mypassword == "") )

 

take both of the exclamation mark off.

 

^ currently it means that, if the username and password is not empty, they will be required to fill in the fields.

it makes no sense right? LOL!

--

you should change to if username and password is empty first, den else { another condition }

 

Anyway, after you echo the 'please fill in the fields' , do not exit;

it will destroy everything after that.

 

Instead you should put it like that

if ( ($myusername == "") || ($mypassword == "") )
echo "Please fill in all fields";

} else { 
//check the form in database

$sql = "SELECT * FROM users WHERE username = '$myusername' AND password = '$mypassword'";

$result = mysql_query($sql);

$account = mysql_num_rows($result);

//check if user exists

if ($account == 1) {

$_SESSION["username"] = $myusername;

$_SESSION["password"] = $mypassword;

$_SESSION["userrecord"] = mysql_fetch_assoc($result);

echo "You have been logged in successfully. Please click <a href=account.php>here</a> to continue.";

} }
Edited by KaiSheng
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.