I am trying to add the form error messages in my html form. Problem is there in first view. In user function html is disappear from where I start to use form_error(). My Original form design is like this: my original form
but after adding the form_error under the first input: my form error image
Here is my html code
<div class="form-group">
<label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label>
<input type="text" name="username" id="name" placeholder="Your Name" />
<?php echo form_error('username','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
<div class="form-group">
<label for="email"><i class="zmdi zmdi-email"></i></label>
<input type="text" name="email" id="email" placeholder="Your Email"/>
<?php echo form_error('email','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
Here is my controller
<?php
class Register extends CI_Controller
{
public function user()
{
$this->load->view('files/registration/signup');
}
public function login()
{
$this->load->view('files/registration/login');
}
public function description()
{
$this->load->view('files/registration/description');
}
public function registerMe()
{
$this->load->helper('form','url');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|alpha|max_length[15]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('re_pass', 'Confirm Password', 'required|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()===FALSE) {
$this->load->view('files/registration/signup');
}
else
{
$this->load->model('RegisterUser');
$this->RegisterUser->registerme($_POST);
}
}
}
?>
you need to load the form helper in signup function too. form_error is a function in form_helper. (this is required for other functions with a form view too)
public function user()
{
$this->load->helper('form');
$this->load->view('files/registration/signup');
}
html is disappeared because there was php error. check your error log when this happens or change codeigniter environment to development in index.php
Related
I have a register_page.php file in the views folder which is just a register form. When you click the register button, and say the password doesn't match, it should that the password doesn't match after clicking the submit button. However, after you type the password and it still doesn't match, it doesn't do anything, it just duplicates the url.
For example
URL when the password doesn't match: http://localhost/dayone/user/register_user
URL when when the password still doesn't match: http://localhost/dayone/user/user/register_user
At this point, the form is empty, all the values are removed and when you press enter without filling anything in, it doesn't show any error, but the URL says: http://localhost/dayone/user/user/register_user
What's causing this?
My user.php controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index()
{
$this->load->view('includes/header');
$this->load->view('register_page');
$this->load->view('includes/footer');
}
public function register_user () {
$this->load->library('form_validation');
//rules to become a registered user
$this->form_validation->set_rules('first_name', 'First Name', 'required|trim|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|trim|min_length[6]|max_length[50]|valid_email|is_unique[users.email]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[6]|max_length[50]|matches[password_conf]|xss_clean');
$this->form_validation->set_rules('password_conf', 'Confirm Password', 'required|trim|min_length[6]|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE) {
//user didn't validate, send back to login form and show errors
$this->load->view('includes/header');
$this->load->view('register_page');
$this->load->view('includes/footer');
} else {
//successful registration
$this->load->view('login');
}
}
}
My resister_page.php (with the register form):
<!DOCTYPE html>
<html lang="en">
<body>
<div id="container" class="page">
<div>
<section class="container">
<h2 class="block-title block-title--bottom">Login</h2>
<div class="login">
<?php echo validation_errors('<p class="alert-market">'); ?>
<form class="contact" id="contact-form" name="contact-form" method="post" action="user/register_user">
<!--- FIRST NAME --->
<input class="contact__field" value="<?php echo set_value('first_name'); ?>" name="first_name" id="first_name" type="text" placeholder="First Name">
<!--- LAST NAME --->
<input class="contact__field" value="<?php echo set_value('last_name'); ?>" name="last_name" id="last_name" type="text" placeholder="Last Name">
<!--- EMAIL --->
<input class="contact__field" value="<?php echo set_value('email'); ?>" name="email" id="email" type="email" placeholder="Email">
<!--- PASSWORD --->
<input class="contact__field" name="password" id="password" type="password" placeholder="Password">
<!--- CONFIRM PASSWORD --->
<input class="contact__field" name="password_conf" id="password_conf" type="password" placeholder="Confirm Password">
<a class="login__callback" href="#">Forgot password?</a>
<input class="btn btn--decorated btn-warning login__btn" value = "Login" name="submit" type="submit">
<?php echo form_close(); ?>
</div>
</section><!-- end container -->
</div>
</div><!-- /#page -->
</body>
</html>
I have no idea what is causing this.
Instead of this one:
<form class="contact" id="contact-form" name="contact-form" method="post" action="user/register_user">
You can use this one:
<?php echo form_open('user/register_user');?>
Which is also equal to this:
<form method="post" accept-charset="utf-8" action="http://localhost/dayone/user/register_user"/>
Assuming that your base_url in your config.php is equal to:
$config['base_url'] = 'http://localhost/dayone/';
I suggest you invest time in reading more about CodeIgniter's User Guide here.
EDIT:
Do not forget to load your form and url helpers too. You can load them in autoload.php in application/config
$autoload['helper'] = array("url","form");
Or
Make a function __contruct() and load your helpers and models there.
Example:
function __construct()
{
parent::__construct();
$this->load->model('sample_model');
$this->load->helper('url');
$this->load->helper('form');
}
Constructors are useful if you need to set some default values, or run
a default process when your class is instantiated. Constructors can't
return a value, but they can do some default work.
--From CodeIgniter - Controllers under Class Constructors
First use form helper to form open
<?php echo form_open('user/register_user');?>
Then change your match password rules like(match confirm password to password):-
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[6]|max_length[50]|xss_clean');
$this->form_validation->set_rules('password_conf', 'Confirm Password', 'required|trim|min_length[6]|max_length[50]|matches[password]|xss_clean');
Then your else part should be a redirect not load a view again like
else {
// success register
redirect('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
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'); ?>
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;
}
}
}
I try to set up a password in a codeigniter form...
Everything seems ok to my eyes but no matter which password I use the form is still submitted...
here is the code in the controler:
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper(array('url','form','html')); //here we load some classes that we use
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->scaffolding('comments');
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('pass', 'Pass', 'callback_pass_check');
function pass_check($str) {
if ($str == 'baywatch'){
return TRUE;
}
else{
return FALSE;
}
}
if ($this->form_validation->run() == TRUE)
{
$this->myBlog_insert();
//$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$insert = array( 'title' => $_POST['title'],
'body' => $_POST['body'],
'author' => $_POST['author']
);
$this->db->insert('entries',$insert);
redirect('myBlog/');
}
}
and this is my form:
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?php echo validation_errors(); ?>
<?php echo form_open('myBlog'); ?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p>
<label for="pass">Password:</label>
<input type="password" name="pass" size="38" id="pass"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
any ideas?
thanks in advance
<label for="pass">Password:</label>
<input type="text" name="pass" size="38" id="author"/>
The input type is text no password, the id='pass'.
Ok, a couple of things first:
1) id's should be unique. ie your author field and your password field shouldn't have the same id.
2) password fileds should use the type "password" not "text".
I think the reason you're having problems is with your callback function pass_check(). Try changing your function to:
function pass_check($pass)
{
if($pass !== 'baywatch')
{
return FALSE;
}
By the way, scaffolding has now been deprecated. Can I suggest you look into using models and the active record class as a way of interacting with your db? Also, this really isn't a very secure way of handling passwords. Have a look at some of the CI authentication libraries and see if you can implement one of them.
Ok guys...I found what the problem was...function pass_check was declared inside index()...and for some reason it needs to be outside as a method of the class...Hope this will help others... I give some ups for all the suggestions...