Home / blog / Membuat Form Login dengan PHP Object Oriented

Membuat Form Login dengan PHP Object Oriented

PHP Merupakan bahasa pemrograman web yang paling populer dewasa ini. banyak yang bisa dilakukan oleh php, mulai dari koneksi ke berbagai macam database manajemen system (DBMS) misal MySQL. disamping itu PHP 5 keatas sudah mendukung yang namanya pemrograman berorientasi objek. nah dalam postingan kali ini kita akan membahas bagaimana cara membuat sebuah form login dengan menggunakan PHP Object Oriented.

1. Langkah pertama : Buatlah file dan direktori sebgai beriku

——-[dir]includes——
config.php
function.php
——[/dir]includes——
login.php
home.php


2. Langkah berikutnya : Masukkan kodingan seoperti dibawah ini :

config.php


Membuat file koneksi ke database :
———————————-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
define('DB_SERVER', 'localhost');   //define your db server here
define('DB_USERNAME', 'root');      //define your db user here
define('DB_PASSWORD', '');          //define your db pass here
define('DB_DATABASE', 'rai');       //define your db name here
 
class DB_class {
    //put your code here
    function __construct()
    {
        $connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
        die('Oops connection error -> ' . mysql_error());
        mysql_select_db(DB_DATABASE, $connection)
        or die('Database error -> ' . mysql_error());
    }
}
?>

 

function.php


membuat file class user untuk dengan fungsi registrasi dan cek login
——————————————————————–

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
include_once 'config.php';
 
class User
{
    //Database connect
    public function __construct()
    {
    $db = new DB_Class();
    }
    //Registration process
    public function register_user($username, $email, $password, $full_name, $no_hp, $website )
    {
        $password = md5($password);
        $sql = mysql_query("SELECT user_id from user WHERE username = '$username' or email = '$email'");
        $no_rows = mysql_num_rows($sql);
        if ($no_rows == 0)
        {
            $result = mysql_query("INSERT INTO user(username, email, password, full_name, no_hp, website)
                                   values ('" . mysql_real_escape_string($username)."',
                                           '" . mysql_real_escape_string($email)."',
                                           '" . mysql_real_escape_string($password)."',
                                           '" . mysql_real_escape_string($full_name)."',
                                           '" . mysql_real_escape_string($no_hp)."',
                                           '" . mysql_real_escape_string($website)."'
                                           )") or die(mysql_error());
            return $result;
        }
        else
        {
            return FALSE;
        }
    }
    // Login process
    public function check_login($emailusername, $password)
    {
        $password = md5($password);
        $result = mysql_query("SELECT user_id from user WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
        $user_data = mysql_fetch_array($result);
        $no_rows = mysql_num_rows($result);
        if ($no_rows == 1)
        {
            $_SESSION['login'] = true;
            $_SESSION['user_id'] = $user_data['user_id'];
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
}
?>

 

login.php


membuat action handle sekaligus form untuk login :
————————————————–

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
session_start();
include_once 'includes/functions.php';
$user = new User();
 
if ($user->get_session())
{
    header("location:home.php");
}
 
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    $login = $user->check_login($_POST['emailusername'], $_POST['password']);
    if ($login)
    {
        // Login Success
        header("location:login.php");
    }
    else
    {
        // Login Failed
        $msg= 'Username / password wrong';
    }
}
?>
                <form method="POST" action="" name="login">
                <tr>
                    <th>Email or Username</th>
                    <td> : </td>
                    <td>
                        <input type="text" name="emailusername"/>
                    </td>
                </tr>
                <tr>
                    <th>Password</th>
                    <td> : </td>
                    <td>
                        <input type="password" name="password"/>
                    </td>
                </tr>
                <tr>
                    <th></th>
                    <td> </td>
                    <td>
                        <input type="submit" value="Login"/>
                    </td>
                </tr>
                <tr>
                    <th>Don't have account?</th>
                    <td> : </td>
                    <td>
                        <a href="./register.php"><b>Register Now</b></a> <br>
                    </td>
                </tr>
                </form>
            </table>

 

home.php


membuat halaman ketika sudah login
———————————-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
session_start();
include_once 'includes/functions.php';
$user = new User();
$uid = $_SESSION['user_id'];
 
if (!$user->get_session())
{
    header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
    $user->user_logout();
    header("location:login.php");
}
?>
<!-- -------HTML------- -->
<a href="?q=logout">Logout</a>

 

database


Membuat tabel database user dengan field sebagai berikut
———————————————————-

1
2
3
4
5
6
7
8
9
10
11
12
mysql_query("CREATE TABLE IF NOT EXISTS user(
                               user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                               username VARCHAR(250) NOT NULL,
                               email VARCHAR(250) NOT NULL,
                               password VARCHAR(250) NOT NULL,
                               full_name VARCHAR(250) NOT NULL,
                               no_hp INT(20) NOT NULL,
                               website VARCHAR(250) NOT NULL,
                               user_type INT(2) NOT NULL,
                               UNIQUE (`email`),
                               UNIQUE (`username`)
                               );");

 
 

18 Responses so far.

  1. Zlumberjay says:

    Kenapa tidak ditutup dengan function
    __destruct(){

  2. Bodrex_20 says:

    saya kok masih banyak yang salah, sebenernya udah di coba pa belum to?

  3. Agung Triadi says:

    variabel $msg ditampilkan di mana? sepertinya tag tidak ada sehingga error.

  4. klewer says:

    mana class register.php nya??

  5. mantsoetoro says:

    gak iso bro

  6. endip says:

    waduh kagak bisa neh bro User::get_session() sessioonya ko ga ada, disini scriptnya sessionnya dah ada

  7. Do you mind if I quote a couple of your posts as long
    as I provide credit and sources back to your weblog?

    My blog site is in the very same niche as yours and my users would
    certainly benefit from a lot of the information you provide here.
    Please let me know if this okay with you. Cheers!