Form Submission and URI rewriting - php

I have a fairly standard CI3 site up and running. I have created my own base controller, called MY_Controller, and all my page controllers extend this.
MY_Controller.php
public function __construct() {
parent::__construct();
}
/**
* Display the view. This function wraps up all the teplates,
* sets the page title, adds all the requested Javascript and CSS,
* and passes along any data.
* #param string $view The name of the content view to display
* #param array $data (Optional) ÏAn array of any data to pass along
*/
protected function showView($view, $data = null) {
if ($data === null) {
$data = array();
}
// call all the template pieces
$this->load->view('header', $data);
$this->load->view('mainNav', $data);
$this->load->view($view, $data);
$this->load->view('footer', $data);
}
Each page controller calls $this->showView($viewName, $data); when it's ready to display results or whatever.
I have a form located on my login controller, Login.php.
Login.php has a method called "submit".
public function submit() {
$cfg = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|trim|alpha_numeric|xss_clean|min_length[3]|max_length[50]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|alpha_numeric|xss_clean|min_length[3]|max_length[50]'
)
);
if ($this->form_validation->set_rules($cfg) === false) {
$this->showView("login");
} else {
$data = array(
'password' => $this->input->post('password')
);
if (filter_var($this->input->post('username'), FILTER_VALIDATE_EMAIL) === false) {
$data['username'] = $this->input->post('username');
} else {
$data['email'] = $this->input->post('username');
}
$user = $this->User->getUserFromLogin($data);
if ($user !== false) {
$sessionData = array(
'userName' => $user->userName,
'email' => $user->email,
'authToken' => $user->authToken,
'lastSeen' => date("Y-m-d")
);
// Add user data to session
$this->session->set_userdata('userLoggedIn', true);
$this->session->set_userdata('userData', $sessionData);
$this->showView("home");
} else {
$data = array(
'error_message' => 'User could not be loaded.',
);
$this->showView("login", $data);
}
}
}
My Login view, login.php
<div class="wrapper style1">
<article id="work">
<header>
<h2>Login!</h2>
<?=validation_errors();?>
</header>
<div class="container 50%">
<section>
<form method="post" action="login/submit">
<div>
<div class="row">
<div class="6u">
<input type="text" name="username" id="username" placeholder="username or email" value="<?=set_value('username');?>" />
</div>
<div class="6u">
<input type="password" name="password" id="password" placeholder="password" />
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" value="Sign in!" />
</li>
</ul>
</div>
</div>
</div>
</form>
<footer>
<div>...or sign in with Facebook!</div>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>
</footer>
</section>
</div>
</article>
</div>
Upon successful submission of the form, I'm expecting it to redirect me to home, which it is, however, the URI is localhost/login/submit instead of localhost/home.
Likewise with my logout controller, upon logout, it navigates to the URI localhost/logout/logout, which generates a 404.
I can't figure out why it doesn't redirect to the controller I've specified in the showView() method.
I'm not using any custom routing tricks.

The method showView simply loads in the values extra templates you want as well as the data you sent. I believe you are looking to do a redirect when you need to move off of pages instead of just rerendering the page the way you are.
redirect($uri = '', $method = 'auto', $code = NULL)
If this doesn't suffice your needs please include you routes and your logout controller to see what's going on in the other scenario you mentioned.

On successful authentication, instead of
$this->showView("home");
you should change that to redirect(),
redirect("controller/method/parameters if any");

there is method call showview(). To load view you have to use
$this->load->view("login");
as well as redirect should be
redirect('controller_name/method_name');

Related

CodeIgniter jQuery validator library not work

anyone can help me how to configure CodeIgniter jQuery validator library
Jquery_validation https://github.com/GuriK/CodeIgniter-jQuery-Validator
my Controller
public function create_action()
{
$now = date('Y-m-d H:i:s');
$data = array(
'nama' => $this->input->post('nama',TRUE),
'email' => $this->input->post('email',TRUE),
);
$this->Register_model->insert($data);
}
my View
<span>
<i><img src="<?php echo base_url();?>assets/frontend/images/name.png" alt="" /></i>
<input type="text" class="textbox" name="nama" placeholder="Nama"></span>
Strongly recommend that First of All "Always Read Documents Carefully"
The Author of CodeIgniter jQuery validator library has clearly mentioned all the necessary steps to get this working except one thing that you have to add jQuery validation plugin in your html head :D Well, for experience players that was unnecessary but for beginner for sure it must be mentioned there..
Step - 1: Download zip file from CodeIgniter jQuery validator
& place library/Jquery_validation.php from there to your
CodeIgniter/application/library/Jquery_validation.php
Step - 2: load this library in your Controller
$this->load->library('jquery_validation'); or you can auto load this
library by putting the code $autoload['libraries'] =
array('jquery_validation'); in
CodeIgniter/application/config/autoload.php.
Step - 3: Create some required code to get this work.
// set validation rule to jquery validation lib
$this->jquery_validation->set_rules($rules);
// set validation message to jquery validation lib
$this->jquery_validation->set_messages($messages);
// create jquery validation script for form #login-form
$validation_script = $this->jquery_validation->run('#login-form');
Step - 4: Don't forget to add jQuery validation plugin in
your view
& finally here is full working example code:
<?php
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
* Class Controller
*
* Class Logins Controller to handle login & logout
*/
class Logins extends CI_controller
{
/**
* Class Constructor
*/
public function __construct()
{
// execute parent class constructor
parent::__construct();
// load helpers
$this->load->helper(array('form', 'url', 'security'));
// load codeigniter for validation lib
$this->load->library('form_validation');
// load jquery validation lib
$this->load->library('jquery_validation');
}
/**
* Default method to execute if method name missing
* #return [type] [description]
*/
public function index()
{
// check if user login or not
if (!$this->session->userdata('name')) {
// form validation rules
$rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
),
array(
'field' => 'pass',
'label' => 'Secret Password',
'rules' => 'required',
),
);
// form validation message
$messages = array(
'name' => array(
'required' => "jQuery validation User Name is required",
'min_length' => "jQuery validation, Please enter more then 3 char",
'max_length' => "jQuery validation, Please enter less then 25 char",
),
'pass' => array('required' => "jQuery validation Password is required"),
);
// set validation rule to jquery validation lib
$this->jquery_validation->set_rules($rules);
// set validation message to jquery validation lib
$this->jquery_validation->set_messages($messages);
// create jquery validation script for form #login-form
$validation_script = $this->jquery_validation->run('#login-form');
// collect script and send to view
$data = ['validation_script' => $validation_script];
// show login view
$this->load->view('form', $data);
}
// if already logged in, show other view
else {
// get name from session login flag
$name = $this->session->userdata('name');
// load view
$this->load->view('form', $name);
}
}
/**
* login Form POST Method to verify Users identity
* #return [type] [description]
*/
public function do_login()
{
// if POST made then only
if ($this->input->post()) {
// form validation rule for codeigniter validation
$rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
),
array(
'field' => 'pass',
'label' => 'Secret Password',
'rules' => 'required',
),
);
// custom validation message for server side form validation
$this->form_validation->set_message('required', 'CodeIgniter validation, The %s is required filed');
$this->form_validation->set_message('min_length', 'CodeIgniter validation, The %s Please enter more then 3 char');
$this->form_validation->set_message('max_length', 'CodeIgniter validation, The %s Please enter less then 25 char');
// form validation using codeigniter built-in lib
$this->form_validation->set_rules($rules);
// check validation
if ($this->form_validation->run() === false) {
// validation failed
$this->load->view('form');
} else {
// safe from CSRF, use 2nd param as TRUE in POST
$name = $this->input->post('name', true);
$pass = $this->input->post('pass', true);
// if result
if ($name == 'admin' && $pass == 'admin') {
$sess_login = array(
'name' => $name,
);
// set session login flag
$this->session->set_userdata($sess_login);
// load view
$this->load->view('form', $name);
} else {
redirect('logins');
}
}
} else {
redirect('logins');
}
}
/**
* Log Out Method
* #return [type] [description]
*/
public function userlogout()
{
$this->session->unset_userdata('name');
redirect('logins');
}
}
/* End of file logins.php */
/* Location: ./application/controllers/logins.php */
& here is view source code:
<?php
$name = $this->session->userdata('name');
?>
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter jQuery validation</title>
<!-- load bootstrap css -->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- load jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- load bootstrap js -->
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- load jquery validation javascript plugin -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<!-- echo jQuery form validation script from Controller -->
<script type="text/javascript">
<?php echo $validation_script;?>
</script>
</head>
<body>
<div class="jumbotron vertical-center">
<?php if ($name !== false): ?>
<div class="container">
<div class="alert alert-success">Wohoo!! You made it.. <?php echo $name ?> Log Out</div>
</div>
<?php else: ?>
<div class="container">
<?php echo (validation_errors()) ? '<div class="alert alert-danger">'.validation_errors().'</div>' : ''; ?>
<?=form_open('logins/do_login', 'id="login-form" class="form-controller"'); ?>
<fieldset>
<legend>Login Information</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Please enter your user name here" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="password">Secret Password</label>
<input type="password" class="form-control" id="password" name="pass" placeholder="Please enter your password here" value="<?php echo set_value('pass'); ?>">
</div>
</fieldset>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button type="submit" class="btn btn-primary">Sign in</button>
</div>
</div>
<?=form_close();?>
</form>
</div>
<?php endif ?>
</div>
</body>
</html>
You can see the demo by using http://localhost/CodeIgniter/logins url in your browser.

Insert into DB with codeigniter 3

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);
}

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

Codeigniter can't login

Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
I have set my base_controller as Login
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function login(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
here is the view
<?php echo validation_errors(); ?>
<form method="post">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
When I click the login button, nothing happens. What am I doing wrong?
You have to give action attribute in form tag, like this:
action="http://yoursitename.com/controllername"
in your case controllername is login.
For more help, you can refer:
[https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html][1]
Hope this help!
this link shows how form_open() works, one of codeigniter's utility functions from the form helper libary.
In your case you would want this line of code:
<?php echo form_open('/login'); ?>
or something that you want to be the login url.
This line would replace
<form method="post">
in your html and when rendered would be something like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/login" />
If you aren't familiar with URI routing, then you should read about that here](https://ellislab.com/codeigniter/user-guide/general/routing.html). I would recommedn setting up a route for you login, but the default format for a url is
example.com/class/function/id/
so yours might look like
example.com/login/login
And form_open() would then look like (even though its kind of cluncky)
<?php echo form_open('/login/login'); ?>
You can try below code
login.php controller file
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function validate(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
Here I have loaded one helper to give action url in view file
$this->load->helper('url');
Also I have changed function name from login to validate as function name should not be similar to class name as constructor is already defined there
login.php view file
<?php echo validation_errors(); ?>
<form method="post" action = "<?php echo site_url("login/validate"); ?>">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
Hope this will help you

User registration with CodeIgniter

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;
}
}
}

Categories