Ok now I will explain about to create simple login using CodeIgniter (Update using codeigniter version 3.0) & Database (Example I use MySQL). And in this case, I think you’ve installed CodeIgniter on your local PC or localhost. Next, just follow this intructions:
- Create Database.
CREATE TABLE `users` ( `id_user` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`id_user`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Note:
Oh ya remember to add one row or data to table admin, example with name “Imron” and password “password” with md5.
INSERT INTO users(username, password) VALUES('Imron',md5('password'));
And for certainty, use the select query to see the data that we have just entered.
SELECT * FROM users; id_user | username | password ---------+----------+---------------------------------- 1 | Imron | 5f4dcc3b5aa765d61d8327deb882cf99 (1 row)
- Configure database on CodeIgniter.
Update the file yourcodeigniter/application/config/database.php in your CodeIgniter installation with your database info:$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'yourusername', 'password' => 'yourpassword', 'database' => 'yourdatabase', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => TRUE, 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
- Set Encryption Key config CodeIgniter
We need set Encryption Key to enable session libraries. Open yourcodeigniter/application/config/config.php/* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = 'learn_ci';
- Then now open yourcodeigniter/application/config/autoload.php and change the code like this:
$autoload['libraries'] = array('session'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in the system/libraries folder or in your | application/libraries folder within their own subdirectory. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url');
Explanations:
This function is used to automatically load helper and library (like url and session) if we run codeigniter. So if we load helper and library in this file, we don’t need to load helper or library manually in all controller like this code:$this->load->helper('url') or $this->load->library('session')
So if we write in this autoload.php, we write enough just once for all controllers.
- Code
Create yourcodeigniter/application/models/Login_model.php:<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * @name: Login model * @author: Imron Rosdiana */ class Login_model extends CI_Model { function __construct() { parent::__construct(); $this->load->database(); } public function validate_user($data) { $this->db->where('username', $data['username']); $this->db->where('password', md5($data['password'])); return $this->db->get('users')->row(); } function __destruct() { $this->db->close(); } }
Explanations:
- Line 13 is using to load database, so with this function we can connect to database with the config is from database.php (above file)
- Line 17-19 is Query builder from ci, if we translate the code, may be like this:
SELECT * FROM users WHERE username = "$data['username']" AND password = "$data['password']"
For more info you can read from this http://www.codeigniter.com/user_guide
- Line 23 is the destructor. This is PHP OOP feature, for more info read this http://php.net/manual/en/language.oop5.decon.php
Then create yourcodeigniter/application/controllers/Login.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * @name Login.php * @author Imron rosdiana */ class Login extends CI_Controller { function __construct() { parent::__construct(); $this->load->model("login_model", "login"); if(!empty($_SESSION['id_user'])) redirect('home'); } public function index() { if($_POST) { $result = $this->login->validate_user($_POST); if(!empty($result)) { $data = [ 'id_user' => $result->id_user, 'username' => $result->username ]; $this->session->set_userdata($data); redirect('home'); } else { $this->session->set_flashdata('flash_data', 'Username or password is wrong!'); redirect('login'); } } $this->load->view("login"); } }
Explanations:
- Line 13, this function is used to load model. In this project we create Login_model.php, so this function is to load it and we using alias. So with the alias we can call the model with this $this->login->namefunction, and if we not using alias we can call the model with $this->login_model->namefunction
- Line 14-15 is using to validate session, so if we have logged in before, then we don’t need login again and the page is redirect to Home controller
- Line 19 is using if we get the post from login page
- Line 20 is to load model, and get the save the result to $result variable
- Line 21-28 is used to check if $result not empty or the user already exist on database, we create the session and go to home page
- Line 29-32 is used if user not in database, so login is failed and back again to login page
- Line 35 is to load form login
Then create yourcodeigniter/application/controllers/Home.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * @name Home.php * @author Imron Rosdiana */ class Home extends CI_Controller { function __construct() { parent::__construct(); if(empty($this->session->userdata('id_user'))) { $this->session->set_flashdata('flash_data', 'You don\'t have access!'); redirect('login'); } } public function index() { $this->load->view('home'); } public function logout() { $data = ['id_user', 'username']; $this->session->unset_userdata($data); redirect('login'); } }
Explanations:
- Line 14-17 is used if the user accesses the home page before login, so the user will be redirect to login page
- Line 20-22 is to load home page if user already login
- Line 24-28 is used if user logout from home page, so we must remove the session
The last is create home page on yourcodeigniter/application/views/home.php:
<!DOCTYPE html> <html> <head> <title>Learn CI</title> </head> <body> <h1>Welcome <?= $this->session->userdata('username') ?></h1> <a href="<?= site_url('home/logout') ?>">Logout</a> </body> </html>
And create login page on yourcodeigniter/application/view/login.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learning CI</title> </head> <body> <?php if(isset($_SESSION)) { echo $this->session->flashdata('flash_data'); } ?> <form action="<?= site_url('login') ?>" method="post"> <label for="username">Username</label> <input type="text" name="username" /> <label for="password"></label> <input type="text" name="password" /> <button type="submit">Login</button> </form> </body> </html>
Very easy if you understand this. 😀
Full Code, download in here https://www.mediafire.com/?luzehcvj301dbwv
Reblogged this on SYNTEK LOCAL and commented:
I found this blog post on imron02’s site and felt it will help for the CodeIgniter Fans! Cheers and Happy Coding!
Hi I did follow your steps but when I try to load (or autoload) database library I get this error:
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346
Any hint?
Ok, there was an error in username. Tku anyways (note: there is a typo, your first query creates a namE_admin and later on you keep using namA_admin.)
Thank you very much for the correction.. I will update the post. 😀
It is appropriate time to make some plans for the longer term and it’s time to be happy. I’ve read this post and if I may just I wish to counsel you few attention-grabbing things or suggestions. Perhaps you could write subsequent articles regarding this article. I wish to learn more things about it!
Sory Damon, now codeigniter is dead, you can read and search on google.. And now I migrate from codeigniter to laravel..
Hi to every body, it’s my first visit of this blog; this website consists of remarkable and really fine stuff in support of readers.
Thank you cliff
Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My website is in the exact same niche as yours and my users would really benefit from a lot of the information you present here. Please let me know if this okay with you. Thanks!
Oh of course not and you can quote it, my blog is open source .. Thank you for visiting my blog..
Your method of describing all in this article is truly nice, every one be capable of effortlessly know it, Thanks a lot.
Your welcome Arnette 🙂
I believe everything published was actually very logical. However, what about this? what if you wrote a catchier post title? I mean, I don’t want to tell you how to run your blog, but suppose you added a title to possibly get a person’s attention? I mean Simple Login using CodeIgniter & Database is a little boring. You ought to look at Yahoo’s home page and note how they write news titles to get viewers to open the links. You might try adding a video or a related pic or two to get readers interested about everything’ve got to say. In my opinion, it would make your website a little bit more interesting.
Thank you for your suggestion, sorry I just beginners in blogging. But I will try your suggestion of. Thank you. 🙂
I just couldn’t go away your website before suggesting that I extremely enjoyed the standard info an individual provide on your guests? Is gonna be again ceaselessly to check out new posts
Thank for visiting my blog steven, I will update this blog later, no I’ve many homeworks.. 🙂
Thanks in support of sharing such a pleasant thinking, paragraph is nice, thats why i have read it fully
What’s up, all the time i used to check webpage posts here in the early hours in the break of day, for the reason that i love to find out more and more.
Now I’m busy working on the thesis, and I hope you understand. And in fact this previous blog is just my personal notes in learning coding. So when I found the problem and I was able to finish it, then I will write on this blog, and while this is my coding is delayed because I had to do some of my homework first. And thank you for the trust you to always visit this blog. Another time, I will write again and will not make you wait a long time. 😀
Hello mates, how is everything, and what you want to say concerning this article, in my view its genuinely amazing in favor of me.
I’ve learn some good stuff here. Definitely worth bookmarking for revisiting. I wonder how much attempt you place to create this type of magnificent informative web site.
Hey there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Thank you for sharing!
hey there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise several technical points using this site, since I experienced to reload the website many times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords. Well I am adding this RSS to my e-mail and can look out for much more of your respective interesting content. Ensure that you update this again very soon.
What browser are you using? I use the chrome and firefox worked fine.
Hello! Someone in my Myspace group shared this site with us so I came to check it out. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Fantastic blog and superb style and design.
What’s up everyone, it’s my first visit at this web page, and post is truly fruitful for me, keep up posting these types of articles or reviews.
If you desire to get a good deal from this paragraph then you have to apply these methods to your won weblog.
whoah this weblog is fantastic i really like reading your posts. Stay up the good work! You know, a lot of individuals are searching around for this information, you can aid them greatly.
Someone essentially lend a hand to make critically posts I might state. This is the first time I frequented your web page and up to now? I amazed with the analysis you made to create this particular post extraordinary. Excellent activity!
Hello, i believe that i noticed you visited my weblog thus i came to return the want?.I am attempting to in finding things to enhance my web site!I suppose its good enough to use some of your concepts!!
If you are going for best contents like I do, only pay a quick visit this web site all the time because it offers quality contents, thanks
Your style is very unique compared to other folks I’ve read stuff from. Thanks for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.
I’m amazed, I must say. Rarely do I come across a blog that’s both educative and interesting, and let me tell you, you’ve hit the nail on the head. The problem is something which not enough men and women are speaking intelligently about. Now i’m very happy I came across this during my search for something relating to this.
Excellent post. I am experiencing some of these issues as well..
Hi, its good article regarding media print, we all be aware of media is a wonderful source of information.
Hi there everybody, here every one is sharing these kinds of knowledge, therefore it’s nice to read this web site, and I used to go to see this blog every day.
This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really loved what you had to say, and more than that, how you presented it. Too cool!
If you are going for finest contents like I do, just visit this website all the time since it offers quality contents, thanks
I’m impressed, I have to admit. Rarely do I come across a blog that’s both equally educative and entertaining, and without a doubt, you have hit the nail on the head. The problem is something that not enough folks are speaking intelligently about. Now i’m very happy I found this during my search for something regarding this.
What’s up to all, the contents existing at this website are genuinely awesome for people knowledge, well, keep up the nice work fellows.
I’ve been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I ultimately stumbled upon this website. Studying this information So i am happy to convey that I’ve a very excellent uncanny feeling I came upon just what I needed. I such a lot unquestionably will make certain to do not omit this site and provides it a look on a continuing basis.
Greetings! Very helpful advice within this article! It is the little changes which will make the most important changes. Thanks a lot for sharing!
i need secure login form by using codeIgniter..please anyone help me as soon as possible
Hi it’s me, I am also visiting this web site on a regular basis, this web page is in fact good and the users are really sharing good thoughts.
Very good blog! Do you have any tips for aspiring writers?
I’m planning to start my own blog soon but I’m a little lost
on everything. Would you propose starting with a free platform like WordPress or go
for a paid option? There are so many choices out there that I’m totally overwhelmed ..
Any suggestions? Appreciate it!
This website is using wordpress, you can look at the URL from this website. I lover wordpress because it’s free, simple and easy to use.. 🙂
is this working with CI 3.0? thanks!
Yes that is work..
I follow your instruction and i got this error “Unable to load the requested file: login.php”
The article is updated.
i have error
unable to load login.php
You can download the complete code at the end of the article
I am now not positive the place you are getting your information, but great topic. I must spend some time learning more or understanding more. Thanks for magnificent information I was looking for this information for my mission.
it’s work. But when I’m filling wrong username & password, I don’t get a warning.
how to resolve it? hehehe
This work perfectly bro. You can see this code if username or password is wrong.
<?php if(isset($_SESSION)) {
echo $this->session->flashdata(‘flash_data’);
} ?>
Very helpfull. Thanks mas Imron