Membuat Form Login dengan PHP dan database MySQL

Berikut ini saya sampaikan tutorial tentang bagaimana cara membuat form login di web menggunakan PHP dan juga databasenya yaitu MySQL. Sebelumnya saya asumsikan bahwa kamu telah mempunyai table admin di scema database dengan kolom username dan password serta diasumsikan bahwa kamu mempunyai akses ke root user.

Pertama-tama kamu perlu untuk mengoneksikan database MySQL, berikut merupakan script konfigurasinya simpan dalam file config.php

<?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'database');
   $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

selanjutnya berikut merupakan script untuk halaman loginnya beserta script php untuk bisa login dengan menggunakan data yang telah ada di database MySQL, simpan sebagai login.php

<?php
   include("config.php");
   session_start();
   
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      // username dan password didapat dari form
      
      $myusername = mysqli_real_escape_string($db,$_POST['username']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
      $sql = "SELECT username FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
      
      $count = mysqli_num_rows($result);
      
      // Jika hasil sesuai $myusername dan $mypassword, table row harus 1	
      if($count == 1) {
         $_SESSION['login_user'] = $myusername;
         header("location: welcome.php");
      }else {
         $error = "Your Login Name or Password is invalid";
      }
   }
?>
<html>
   <head>
      <title>Login Page</title>
      <style type = "text/css">
         body {
            font-family:Arial, Helvetica, sans-serif;
            font-size:14px;
         }
         
         label {
            font-weight:bold;
            width:100px;
            font-size:14px;
         }
         
         .box {
            border:#666666 solid 1px;
         }
      </style>
   </head>
   <body bgcolor = "#FFFFFF">
      <div align = "center">
         <div style = "width:300px; border: solid 1px #333333; " align = "left">
            <div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>			
            <div style = "margin:30px">
               <form action = "" method = "post">
                  <label>UserName  :</label><input type = "text" name = "username" class = "box"/><br /><br />
                  <label>Password  :</label><input type = "password" name = "password" class = "box" /><br/><br />
                  <input type = "submit" value = " Submit "/><br />
               </form>
               <div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>				
            </div>
         </div>	
      </div>
   </body>
</html>

 

Setelah kamu bisa login maka halaman welcome.php ini akan ditampilkan

<?php
   include('session.php');
?>
<html">
   <head>
      <title>Welcome </title>
   </head>
   <body>
      <h1>Welcome <?php echo $login_session; ?></h1> 
      <h2><a href = "logout.php">Sign Out</a></h2>
   </body>
</html>

 

Berikut merupakan script untuk bisa logout dari session login, impan sebagai logout.php

<?php
   session_start();
   if(session_destroy()) {
      header("Location: login.php");
   }
?>

 

Dan, berikut session.php akan memverifikasi session, jika tidak ada sesion maka  akan redirect ke halaman login

<?php
   include('config.php');
   session_start();
   
   $user_check = $_SESSION['login_user'];
   
   $ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
   
   $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
   
   $login_session = $row['username'];
   
   if(!isset($_SESSION['login_user'])){
      header("location:login.php");
   }
?>


Berikut merupakan screenshot hasil dari script login.php
loginsedangakan hasilnya apabila berhasil login akan menampilkan halaman welcome.php
welcome
apabila ingin logout maka akan redirect ke page login.php

Selamat mencoba :)



You may also like...

10 Responses

  1. Вау! Я действительно наслаждаюсь скачивая шаблоны и
    темы этого сайта. Они просты, но эффективны для оформления.
    Часто сложно найти “идеальный баланс” между комфортом использования и визуальной составляющей
    ресурса. Я должен сказать, что этот человек проделал невероятную работу над материалом.
    Кроме того, процесс загрузки потрясающе скоростной, у меня браузер Опера.

    Превосходный блог!

  2. click says:

    You’ll be able to discover cam girls, gay guys, couples, groups,
    trans cams, and many other kinds of individuals performing on Xcamy.

    Every stay cam you see on Xcamy is a real
    particular person performing sex reveals from their residence.

    asian sexy vedio http://translate.wikifab.org/index.php/User:DonnieBeaver

  3. For the time being DVD comes in 8 flavors: DVD-1, DVD-2, DVD-3, DVD-4, DVD-5,
    DVD-9, DVD-10 and DVD-18. Curiously that is about the same second when parents began shuffling
    their screaming children out of the theater. I lastly grasped how actually
    horrible this was once i noticed strange girls slowly wheel their kids away from me once i sang some lyrics jokingly to my boyfriend on the supermarket.
    It’s a ethical saga that makes my thoughts as we speak want to implode, I can solely imagine what it does to youngsters.
    This is not to say the fairy-killing can of Raid, the hoarder
    muppet that lives within the dump, or the loopy probably LSD impressed scene where a bunch
    of muppets start lopping off physique elements and throwing them at each other.
    I have to start this by saying that Alice in Wonderland was written by a
    math genius and given to a ten year outdated woman as a Christmas present. https://legalporno.top/tags/hardcore/

  4. here says:

    Now you’re only one click on away from the very best porn watching expertise you’re ever going to
    have. No more of that, now all the things is accurately.
    There is not any better place to download free anti malicious
    software software program than from Google You can study extra from the hyperlink below.
    That is considered one of the moment Message Blocking software
    making your computer systems (that will include upto
    50 of them within the group) that you could be use for
    the smal or any of your personal utilization, that you
    could be better consider.businesses, properties, education. Spy Mature Clips Tube have incredibly hot free mature porn tube films when you think
    that sex ought to be natural, free and wild. We take satisfaction in our solely purpose to be your pleasure, so this website
    is totally freed from cost. If you’re taking satisfaction in being the
    passionate porn watcher, then listen up about what we have now in inventory from you. https://www.vulpyx.com/cougar-chicks-horny-as-ever-throw-a-masquerade-party/

  5. here says:

    Hundreds of HD, wide FOV videos are at your fingertips,
    and you’re simply seconds away from an all natural babe riding your cock
    cowgirl or supplying you with a Hot footjob! It doesn’t matter what
    you’re craving, we’ve acquired one thing on your tastes.
    We’ve acquired porno content material able to stream to your
    Oculus Quest, Valve Index, HTC Vive / Vive Professional,
    Rift S, Gear VR, PSVR, or Google Cardboard compatible
    units with just some clicks! Plus all 30FPS content has been upgraded to 60FPS.
    60 FPS 5K VR porn is the default now on SLR, with some
    movies even accessible in 90FPS to take advantage of the 90Hz show price available to desktop-powered headsets like Oculus Rift and HTC
    Vive. You’ll be able to watch your bought movies through your account on any VR
    headset through the use of the SLR, which provides you an unparalleled VR video watching experience.
    Do not drive on them what you see in the sex movies online, mental pleasure is more important right here than bodily
    pleasure. https://www.sexualcase.com/puremature-busty-milf-real-estate-agent-pounded/

  6. click says:

    Teen porn is all about 18 and 19 yr old amateurs and pornstars showing off their overactive libidos and tight bodies in hardcore intercourse movies.
    Whether you want 18 12 months old girls or sixty five yr old women,
    it is all obtainable for viewing completely different niches of free sex motion pictures.
    We don’t have any management over the free sex content material of those pages.
    We now have full video collections from top adult tubes: Pornhub, Xhamster, Xvideos, Youporn, Redtube and others.
    There’s nothing fairly like the giggling that may erupt in a room full of school students that have been told to
    watch a training video manufacturing that appears like Ladyhawke and appears like a foul crime scene recreation. It has been observed that the lack of curiosity to have intercourse
    could be triumphed over by taking part in free intercourse movies and watching them together with the respective companions.
    In a world the place every little thing is changing so
    rapidly we’re ready to give you the most in depth and vast choice of sex
    movies for any style and selection. https://www.masturporn.com/no-pussy-for-this-anal-whore/

  7. Try our new podcast, I want It That Method, which delves into the troublesome
    and downright soiled elements of a relationship,
    and discover more on our Soundcloud web page. The sexual deviant
    splinter cell of the Bronies are often called “Cloppers.” According to
    PornHub’s findings men usually tend to be
    Cloppers than girls and are, on common, between 18 and 24.
    Simply to make clear one thing, as I did not realize this myself, MLP porn includes real human women dressed as
    ponies. The research discovered that most Cloppers are from the U.S.
    U.Ok., but, for whatever reason, there are particularly enthusiastic communities in Belarus, Russia and
    the Ukraine. We’ll continue including games to this breakdown as
    often as we find actual winners, guaranteeing that
    you are only ever playing the best My Little Pony video
    games on the market. Pony video games are so well-liked these days
    (especially after the launch of the My Little Pony: Friendship Is Magic animated collection that was recently unveiled) there are many My Little Pony video games catering
    to children and teenagers – but discovering My Little Pony games with a distinct grownup bent to
    them isn’t quite as simple as you might need hoped.
    So there you have got it. https://www.anal4us.com/videos/293560/badabby-gets-a-bbc-backdoor-jam/

  8. To be able to slim down the selection, you possibly can at all times use our search
    engine as effectively – find any key phrase or
    porn tag that you really want, it’ll only take a few seconds.
    There are thousands of hardcore tube videos here and each is unique and you can search and browse so long as you want.

    Great assortment of Pornstars like Aaliyah Hadid, Aaliyah
    Love, Aaralynn Jewel that are properly organized and mobile friendly on any device, as soon as
    once more do not forget that it’s all Full HD and VR Porn movies and 4K quality.
    Best porn films and XXX clips starring mature girls.
    Whether or not these nude women need large cocks or a dripping
    wet pussy to dive into, we don’t care! 4. Female fans that want to
    exhibit their tits, pussy or ass are welcome to send me their nudes.
    There are some really bizarre issues in here, like women forced to do
    a Television show while guys are jerking off next to them and rubbing their pussies with vibrators, to put an example.
    Now we have a great collection of Pornstars like Marica Chanelle, Alexis Zara, Carrie
    which might be effectively organized and cell friendly on any machine, once once more remember that it’s
    all Full HD and VR Porn films and 4K quality. https://milfanaliz.com/videos/34615/marie-instagrameuse/

  9. Count on the perfect mixture of the highest premium porn websites, porn tubes,
    and the very best free porn sites. Based on probably the
    most searched pornographic content on these porn tubes, I created the assorted categories on The PornDude.

    FapToo army, unfold the phrase on any social media platforms, and make The PornDude world-well-known. Bookmark
    The PornDude as your homepage and proudly show it off like a boss,
    as in the event you have been president Trump grabbing bitches by the pussy!
    Then, when I am finally capable of stream the porn tube video, the quality seems to
    be prefer it was captured with a potato cam from the 90s.

    Also, more often than not, the video solely lasts a
    few minutes, or the video participant has fixed hiccups, which makes it inconceivable to fap one-off!
    If something seems “strange” on a porn tube or any free intercourse websites, it normally is!
    Most porn is about watching girls pretend
    to enjoy sex acts which can be unpleasant to them.
    The males who’re obsessed with pornography choose excess masturbation. Over masturbation results are
    fairly devastating in nature and that cannot be discussed openly.
    These capsules additionally act as the most effective antidepressants and thus mental disorders are
    being effectively regulated and diminished in order that extreme
    masturbation could be minimized which is the main reason for inviting erectile dysfunction. https://www.bigassex.com/videos/fuck-my-wife/

  10. Ruslanpbg says:

    Доброго времени суток друзья[url=https://comfortlife.by/]![/url]
    Изготавливаем и устанавливаем любые зеркала под заказ в Минске и области по необходимым вам размерам. Предлагаем вам максимально широкий ассортимент оттенков зеркал, различные формы, технологии обработки и декорирования. С удовольствием беремся за нестандартные и оригинальные индивидуальные проекты.
    Более подробная информация размещена https://drive.google.com/file/d/13CAPanRKgpkKCcaHzI0EiaMtWM0saPJO/view?usp=sharing
    С уважением,коллектив «КОМФОРТЛАЙФ».

Leave a Reply

Your email address will not be published. Required fields are marked *