I'm trying to build a registration system with CodeIgniter. I have a controller called Register with the following code:
class Register extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
$this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
$this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
$this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
$this->load->view('header');
if(!$this->form_validation->run())
{
$this->load->view('register_form');
}
else
{
$this->load->view('register_done');
}
$this->load->view('footer');
}
}
So far so good. If I go to the register page I get the registration form displayed. If I send the form and it passes the form validation checks, I get the success page, if the form has errors, I get the form back with some error messages.
Now what I want to do is the database stuff. I have some idea of how I can get the POST values from the registration form into my database, but no clue how I can check if a username or email already exists, and if so, display that error on the registration form. Here's my registration form view:
<?php $this->load->helper('form'); ?>
<?php echo form_open('register'); ?>
<ul id="register">
<ul>
<h3>Account information</h3>
<li>
<label for="username">Choose a username</label>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" />
<span class="desc">The name you'd like to be known by</span>
<?php echo form_error('username'); ?>
</li>
<li>
<label for="password">Pick a password</label>
<input type="password" name="password" />
<span class="desc">The best passwords are random and more than 6 characters long</span>
<?php echo form_error('password'); ?>
</li>
<li>
<label for="email">Enter your valid email address</label>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" />
<span class="desc">We'll send you an activation email</span>
<?php echo form_error('email'); ?>
</li>
</ul>
<ul>
<h3>About you</h3>
<li>
<label for="band">Who's your favorite artist?</label>
<input type="text" name="artist" value="<?php echo set_value('artist'); ?>" />
<span class="desc">Don't put Lady GaGa.</span>
<?php echo form_error('artist'); ?>
</li>
</ul>
<ul>
<h3>Security question</h3>
<li>
<label for="captcha">Enter the letters you see in the image</label>
<?php $this->load->helper('captcha');
$cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
$data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo $cap['image']; ?>
<input type="text" name="captcha" />
<?php echo form_error('captcha'); ?>
</li>
</ul>
<ul>
<h3 class="submit">
<input type="submit" value="Register" />
</h3>
</ul>
</ul>
<?php echo form_close(); ?>
As you can see, I'm taking advantage of the form_error() function of CI to display form errors right under the field, and I would like the "username already exists" error to also be displayed under the username field.
Can anyone provide some help? Even a nudge in the right direction?
Thanks!
I would strongly urge you to think about using another library that already does this very well: TankAuth. TankAuth is easily modifiable and offers email confirmation, very secure password hashing, a solid database schema, and very clean code.
There's no reason to reinvent the wheel, especially when it comes to something that's very hard to get right like user authentication.
EDIT:
For example, here's everything TankAuth provides security-wise that you'd have to code yourself (if you cared about security) - how much time would that take?
Using phpass library for password hashing (instead of unsafe md5).
Counting login attempt for bruteforce preventing (optional). Failed login attempts determined by IP and by username.
Logging last login IP-address and time (optional).
CAPTCHA for registration and repetitive login attempt (optional).
Unactivated accounts and forgotten password requests auto-expire.
You need to create a model for your controller.
Your model would look like this:
class Register_model extends CI_Model {
function register_user()
{
$data['username'] = $this->input->post('username');
$data['password'] = sha1($this->input->post('password'));
... (your other post data) ...
$this->db->insert('users', $data);
}
}
In your controller you will call the model this way:
$this->load->model('Register_model');
and the method goes here:
else
{
$this->Register_model->register_user();
$this->load->view('register_done');
}
If you want to check if the username is available, you simply put SELECT query on the first lines of the register_user() method (function).
To do the check you should have functions in your model that can look up those types of things for you:
class Model{
function getUserByEmail($email);
function getUserByUsername($username);
...
}
Then in your controller you can call these methods
...
$result = $model->getUserByEmail($_POST['email']); // You'll need to sanitize your POST
if(count($result) > 0){
// Sent error about email already existing and flag to not insert/update user
}
...
The easiest solution in CodeIgniter is to use a callback function as one of the rules in your form validation.
I've used this method myself to check the username and e-mail.
Here's the docs for it.
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('User_model');
}
public function index()
{
$this->load->view('index');
}
public function project()
{
$this->data['posts'] = $this->User_model->getPosts(); // calling Post model method getPosts()
$this->load->view('tables', $this->data);
// $this->load->aview('project');
}
public function get_project()
{
$this->User_model->get_project($data);
}
public function signin()
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$this->User_model->signin($data);
}
public function logout()
{
$this->session->unset_userdata($_SESSION['email']);
// $this->session->sess_destroy();
redirect('User');
}
public function signup()
{
$data = array(
'name' => $this->input->post('name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
if($this->User_model->signup($data))
{
echo "no insert";
}
else
{
$this->load->view('index', $data);
}
}
}
<?php
Class User_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->library('session');
}
public function signup($data)
{
$this->db->insert('user_signup',$data);
}
public function getPosts()
{
$this->db->select("*");
$this->db->from('user_data');
$query = $this->db->get();
return $query->result();
}
public function signin($data)
{
$this->db->where('email',$data['email']);
$this->db->where('password',$data['password']);
$query=$this->db->get('user_signup');
if($query->num_rows()==1){
$_SESSION['email'] = $data['email'];
$this->load->view('popup',$data);
return true;
}
else{
echo "no";
return false;
}
}
}
Related
controller: Test.php
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user();
$this->load->view('home');
}
}
?>
Model: User_model.php
<?php
class Users_model extends CI_Model
{
public function insert_user()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
return $this->db->insert('user', $data);
}
}
?>
view: home.php
<form method="post">
<label for="name">your Name</label>
<input class="form-control" id="name" type="text" placeholder="Name" name="name" />
<label for="email">Your email</label>
<input class="form-control" id="email" type="text" placeholder="Email" name="email" />
<label for="message">Your Message</label>
<textarea class="form-control" id="message" placeholder="Message" name="message"></textarea>
<button type="submit">send</button>
</form>
I am new in codeigniter here I want to insert form value into database but it showing some error i.e.
how can I fix this error ? please help.
Thank You
You got the errors because you call User_model->insert_user() before any data submitted in the form. You should check if there is any posted data then save to the database. Here is the example of your controller should be:
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
// do checking right here
if (!empty($this->input->post('name'))) {
$this->Users_model->insert_user();
}
$this->load->view('home');
}
}
You forget to pass POST data in insert method of model in controller .
Contoller
<?php
class Test extends CI_Controller {
public function index()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'message' => $this->input->post('message')
);
$this->load->helper(array('form', 'url'));
$this->load->model('Users_model');
$this->Users_model->insert_user($data );
$this->load->view('home');
}
}
Model
<?php
class Users_model extends CI_Model
{
public function insert_user($data = [])
{
return $this->db->insert('user', $data);
}
}
?>
You extend CI_Model But did not call parent construct. Use this:
function __construct() {
// Call the Model constructor
parent :: __construct();
}
Hope this will work. Thanks.
In your "home.php" you haven't specify an action attribute. Due to this form value is not posting.
for example:- <form action="<?php echo base_url();?>YourfileName/DeclaredFunctionName" method="post">
and then try to fetch the value of your form in your controller.
In controller please execute this function insert_user() { print_r($_POST); exit(); }
If you are getting values in your browser, then remove exit() and execute your code. Otherwise, please share your error here.
Thanks
im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}
I've been following this tutorial on simple login using CodeIgniter
http://www.iluv2code.com/login-with-codeigniter-php.html.
Whenever I click the login button, I get redirected to a blank page instead of getting to the "verifylogin" controller. I tried to change form_open('verifylogin') to form action="verifylogin" just to make sure it reaches the verifylogin. It reaches verifylogin but can't seem to be doing the correct functionalities. Why is that so? Why am i redirected to a blank page when the form is submitted?
Thank you!
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->load->helper(array('form'));
$this->load->view('login_view');
}
}
?>
View
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple Login with CodeIgniter</title>
</head>
<body>
<h1>Simple Login with CodeIgniter</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="passowrd" name="password"/>
<br/>
<input type="submit" value="Login"/>
</form>
</body>
</html>
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('user','',TRUE);
}
function index() {
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->load->view('login_view');
} else {
//Go to private area
redirect('home', 'refresh');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
sometimes index.php prefix before the your page to avoid this use base_url() function before calling the page in form_open();
like :
echo form_open(base_url()."contact-us");
but before using base_url() make sure that you have called $this->load->helper('url'); in your associate controller.
change this:
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
to:
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
The xss_clean is probably causing the issue, hope it helps. Also make sure if you have not configured your .htaccess file to remove index.php from the url you need to use form_open('index.php/verify_login')
Did you load the url helper??
$this->load->helper(array('url', 'form'));
check it and let me know please
I am trying to keep field values after validation errors on redirect. Validation error shows fine but I keep loosing field values
Form:
<form>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo set_value('v_item_title'); ?>" />
<input type="submit" value="Submit">
</form>
Controller:
$this->load->helper('security');
$this->load->library('form_validation');
$this->form_validation->set_rules('v_item_title', 'Property title', 'trim|required|xss_clean|max_length[100]');
if($this->form_validation->run() == FALSE)
{
$this->session->set_userdata('validation_errors', validation_errors());
$this->session->mark_as_flash('validation_errors'); // data will automatically delete themselves after redirect
$this->session->set_flashdata('v_item_title', $this->input->post());
$this->session->flashdata('v_item_title');
redirect('user/dashboard#new');
} else {
Redirects to
public function dashboard()
{
if($this->session->userdata('is_logged_in')){
$data['validation_errors'] = $this->session->userdata('validation_errors');
$data['v_item_title'] = $this->session->userdata('v_item_title');
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
}else{
You have form validation wrong on controller you have your success info on false area it should be in true area like
http://www.codeigniter.com/user_guide/libraries/form_validation.html
Not sure what your controller name is so I named example login
application > controllers > Login.php
<?php
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->library('session');
$this->load->library('form_validation');
}
public function index() {
$data['title'] = 'Login';
$this->form_validation->set_rules('name_check_box', '', 'trim|required|callback_checkbox');
$this->form_validation->set_rules('v_item_title', 'Property title', 'trim|required|xss_clean|max_length[100]');
if($this->form_validation->run() == FALSE) {
// Load the view
$this->load->view('header', $data);
$this->load->view('login', $data);
$this->load->view('footer');
} else {
$data = array(
'is_logged_in' => true,
'validation_errors' => validation_errors(),
'v_item_title' => $this->input->post('v_item_title')
);
$this->session->set_userdata($data);
// data will automatically delete themselves after redirect
$this->session->mark_as_flash('validation_errors');
// You could set the title in session like above for example
$this->session->set_flashdata('v_item_title', $this->input->post('v_item_title'));
// Echo flash data on view file?
// $this->session->flashdata('v_item_title');
// Dashboard will be a separate controller
// application > controllers > user > Dashboard.php
redirect('user/dashboard');
}
public function checkbox() {
if (isset($_POST['name_check_box']) {
return true;
} else {
$this->form_validation->set_message('checkbox', 'Check box needs to be checked');
return false;
}
}
}
View
http://www.codeigniter.com/user_guide/helpers/form_helper.html
<?php echo form_open('login');?>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo set_value('v_item_title'); ?>" />
<input type="checkbox" name="name_check_box"> Something <br>
<input type="submit" value="Submit">
<?php echo form_close();?>
Note: you may need to set custom routes in application > config >
routes.php
http://www.codeigniter.com/user_guide/general/routing.html
Try this
VIEW
<form>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo $this->session->flashdata('v_item_title'); ?>" />
<input type="submit" value="Submit">
</form>
Make sure that you load the session library and form helper
i have same issue. i applied this logic and its works for me
Change your add and edit method like this...
public function add(){
$college = $this->session->flashdata('data');
$this->load->view("college_add", compact('college'));
}
public function edit(){
$college_id = $this->uri->segment(3);
if($college_id)
{
$college = $this->session->flashdata('data');
if(empty($college))
$college = $this->college->get_college_details_secure($college_id);
$this->load->view('college_add', compact('college'));
}
else
redirect('college/add');
}
And Your save method redirect like this..
if ($this->form_validation->run() != TRUE)
{
$this->set_flashdata("message","Ooopps... form validation failed.".validation_errors());
$this->session->set_flashdata('data', $this->input->post());
if($college_id == '')
redirect("college/add");
else
redirect("college/edit/$college_id");
}
I am working with Codeigniter and on top of it I have Bonefire (could this be the problem?), problem is everytime I want to validate the form with the use of Codeigniters helpers first condition of my conditional runns (FALSE) and on top of that function validation_errors() isn't ran... It is like my libraries for this helper aren't even loaded, despite doing everything by the book:
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
Let me post my form first (I ommited inline styles and classes by purpose):
<div class="" style="">
<h1 id="header" class="">Login/Register</h1>
<form action="/public/index.php/users/sportappregister" >
<div style=""><input id="email" type="text" name="email" value="email" style=""></div>
<div style=""><input id="pass" type="text" name="password" value="password" style=""></div>
<div style="" class=""><img class="" style="" src="<?php echo img_path(); ?>ikone/fb_login_icon.png" />Login with Facebook</div>
<div id="send" style="" class=""><input type="submit"> Submit </div>
<div id="cancel" style="" class=""> Cancel </div>
</form>
</div>
And as you can read from form action my controller is located in file "users" under public class "sportappregister", class Users extends Front_Controller as usuall and in this class at the end I make my own function to handle form like so:
public function sportappregister(){
$email= ($this->input->get("email"));
$pass = ($this->input->get("password"));
$data = array(
"email" => $email,
"password" => $pass );
// here I load my helper
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// rules for my form
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
}
You are using `GET` method. codeigniter form validation works with `POST` method only.
use CI form tags such as form_open() form_close() etc. to build form.
you can check This link
using get for login form will make your app insecure.
rest of your code seems ok to me.
just change this
$email= ($this->input->post("email")); //changed get to post in both
$pass = ($this->input->post("password"));
There's a few things I would change. Read the comments in the amended function below;
public function sportappregister()
{
// Load these first
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Now set the rules
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ( $this->form_validation->run() == false )
{
echo validation_errors();
}
else
{
// Build the array after the form validation
$data = array(
'email' => $this->input->post('email'), // POST, not GET
'password' => $this->input->post('password')
);
// Load your model
$this->load->model('users_model');
if ( $this->users_model->insert($data) )
{
echo 'Registration successful';
}
else
{
echo 'Registration failed';
}
}
}
You have also loaded the form helper, but you're not using it. It makes building forms much, much easier.
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
<?php echo form_open('users/sportappregister'); ?>