execute another function within function with data variables - php

need help on this one:
here's a my sample code,
i would like to add a validation message if a preg_match occurs:
pls. see inline comments for more details..
public function supplier_entry()
{
if (preg_match("/[\'^£#&*...etc.../", $this->input->post('supplier')))
{
//add or pass validation message, ex. $msg = 'Invalid Supplier Name';
// i tried $this->supplier_entry_form($msg); but its not working.
$this->supplier_entry_form();
}else{
$post_data = array(
'supplier_name' =>$this->input->post('supplier'),
'user' => $this->input->post('user'),
'trx_id' =>$this->input->post('trx_id'),
);
$this->load->model('user_model');
$this->load->model('product_model');
$this->product_model->add_new_supplier($post_data);
$user_data['trx'] = 'Supplier Entry';
$user_data['username'] = $this->user_model->user_info();
$trx_data['supplier'] = $this->product_model->get_supplier_list();
$trx_data['msg'] = 'Supplier Posted.';
$this->load->view('header',$user_data);
$this->load->view('item_supplier', $trx_data);
}
}
thanks in advance..
public function supplier_entry_form()
{
$this->load->model('user_model');
$this->load->model('product_model');
$user_data['username'] = $this->user_model->user_info();
$user_data['trx'] = 'Supplier Entry';
$trx_data['supplier'] = $this->product_model->get_supplier_list();
$this->load->view('header', $user_data);
$this->load->view('item_supplier', $trx_data);
}

Use the built in form validation.
$this->load->library('form_validation');
$this->form_validation->set_rules($this->input->post('supplier'), 'Supplier', 'trim|callback_pregMatchSupplier');
if($this->form_validation->run()==FALSE)
{
$this->supplier_entry_from();
}
// continue code here if validation passes.
function pregMatchSupplier()
{
if (preg_match("/[\'^£#&*...etc.../", $this->input->post('supplier')))
{
return FALSE;
} else {
return TRUE;
}
Then in the view you echo out the validation errors:
<?php echo validation_errors(); ?>
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Related

How to compare form input data to database data in a custom codeigniter form validator?

Edit: Some naming had been mixed up in my attempts to solve it myself. I've fixed the callback etc naming and the same error persists.
I am attempting to create a login page for my codeigniter website. I already have a registration page that correctly inputs usernames and passwords in to a "users" table. I am having issues understanding the syntax of creating the functions needed for custom form validators.
My error is "Unable to access an error message corresponding to your field name" for the password and username custom validators.
Here is the relevant part of the controller "login_ctrl"
class login_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login_mdl');
}
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_userCorrect');
//Validating Password Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_passwordCorrect');
//variables to pass form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//reload login page if validation fails
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
//functions for custom validation
function userCorrect($username) {
$this->load->library('form_validation');
//the loads the model that contains the function to compare input to database data
$userExists = $this->login_mdl->userExists($username);
if ($userExists) {
$this->form_validation->set_message(
'userCorrect', 'correct user.'
);
return true;
} else {
$this->form_validation->set_message(
'userCorrect', 'not a valid user name.'
);
return false;
}
}
function passwordCorrect($password) {
$this->load->library('form_validation');
$passwordExists = $this->login_mdl->passwordCorrect($password);
if ($passwordExists) {
$this->form_validation->set_message('passwordCorrect', 'correct password.');
return true;
} else {
$this->form_validation->set_message('passwordCorrect', 'invalid password.');
return false;
}
}
This is the corresponding view "login"
<?php echo form_open('login_ctrl'); ?>
<h1>Login</h1><hr/>
<?php if (isset($message)) { ?>
<?php } ?>
<?php echo form_label('User Name :'); ?> <?php echo form_error('username'); ?><br />
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?><br />
<?php echo form_label('Password :'); ?> <?php echo form_error('password'); ?><br />
<?php echo form_input(array('id' => 'password', 'name' => 'password')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
Finally, this is the corresponding model "login_mdl" (I think the issue might be in this guy).
<?php
class login_mdl extends CI_Model{
function __construct() {
parent::__construct();
}
function userExists($username) {
$this->db->select('id');
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
function passwordCorrect($password) {
$this->db->select('password');
$this->db->where('username', $username);
$query = $this->db->get('users');
$result = $query->row();
return $result->password;
if ('password' == $password) {
return true;
} else {
return false;
}
}
}
?>
I think my issue is related to the db calls and if statements but I've been reading documentation and failing at fixing this for hours so a new pair of eyes would be greatly appreciated.
You need to make your fieldname on your costume rules function is same as your function callback. So, it’s should be like this :
$this->form_validation->set_message(
'userCorrect', 'correct user.'
Do same thing on your other function.

Form Validation Call Back Function Not Working

Here Is My COde I m checking username is already exist or not in datbase
when i validate and submit the form duplicate entry entered in database i want that if already exist it show validation error
My Controller
public function index()
{
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'User Name', 'callback_checkuser');
$this->form_validation->set_rules('role', 'Role', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run()==TRUE)
{
$user['u_name'] = $this->input->post('name');
$user['role'] = $this->input->post('role');
$user['password']= md5($this->input->post('pass'));
$u_id = $this->custom_model->add_user($user);
if($u_id){
$data['msg'] = 'Successfully Created!!!!';
}
}
}
$this->load->template('add_user', $data);
}
function checkuser($name) {
if($this->custom_model->check_name($name) == false) {
false;
}else {
$this->form_validation->set_message('checkuser', 'This user already exist');
return true;
}
}
Here is My Model
public function check_name($name) {
$sql = "SELECT * FROM users WHERE u_name='".$name."' ";
$query = $this->db->query($sql);
$res = $query->row_array();
if (is_array($res) && count($res) > 0){
return $res;
}
return false;
}
There is a return statement missing in the function checkuser, but more importantly, you should invert the value you return. According to the example in the docs, when you set a validation message because of a validation error, you should return false, and return true when the validation passes.
So add a return, and change the boolean values. BTW, you don't really need an else clause and the word "exist" needs an additional "s":
function checkuser($name) {
if ($this->custom_model->check_name($name) == false) {
return true; // the user does not yet exist, so all is OK
}
$this->form_validation->set_message('checkuser', 'This user already exists');
return false; // this is a duplicate user name: not OK
}
Use this:
$this->form_validation->set_rules('name', 'User Name', 'trim|required|is_unique[users.u_name]');// trim and required added too
Docs.

Captcha in Codeigniter can't verify text

I am trying to add a captcha for my login form in codeigniter.
The captcha is displaying fine. and problem is in verifying it.
When validate_captcha is being called the value from input post is correct but session value is new page value.(For example , if on the 1st page load captcha was 12345 (let's assume in second load it will be 54321) . then when in first load user inputs 12345 it will be checked with 54321.
What can I do?
Here is what I have tried
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function index()
{
$capCode = rand(10000, 99999);
$this->session->set_userdata(array('captcha'=>$capCode));
echo $this->session->userdata['captcha'];//for debug only
$this->load->helper('captcha');
$vals = array(
'word' => $capCode ,
'img_path' => CAPTCHA_PATH,
'img_url' => base_url().CAPTCHA_PATH,
'img_width' => '150',
'img_height' => 30,
'expiration' => 1200
);
$cap = create_captcha($vals);
$data = array('un' => $un,'defTab'=>'','captcha'=>$cap);
$this->load->library('form_validation');
//I need to load different data if form is result of a post($data['defTab'])
if($this->input->post('submit'))
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('captcha', 'Captcha', 'required|callback_validate_captcha');
if ($this->form_validation->run() == FALSE)
{
$data['defTab'] = 'what i need';
$this->load->view('login',$data);
}
else
{
print_r($this->input->post());
}
}
else
{
$this->load->view('login',$data);
}
}
public function validate_captcha()
{
$sss=$this->input->post('captcha');
//I Use this line to find problem
$this->form_validation->set_message('validate_captcha', 'session:'.$this->session->userdata['captcha'].'\nPosted val:'.$sss);
if($sss!= $this->session->userdata['captcha'])
{
return false;
}
else
{
return true;
}
}
}
You have to set the session during creation of your form:
.
.
.
} else {
if (isset($cap["word"])) {
$this->session->set_userdata("word", $cap["word"]);
}
$this->load->view('login',$data);
}
And during the validation check it with:
if($this->input->post("word", TRUE) == $this->session->userdata("word")){
// do something
}
Before calling the create_captcha method use the below code to set the previous captcha
$this->session->set_userdata('prev_captcha',$this->session->userdata('captcha_word'));
provided captcha_word contains current captcha
and check like below
function checkCaptcha($str){
$word = $this->session->get('prev_captcha');
if(strcmp(strtoupper($str),strtoupper($word)) == 0){
return true;
}else{
return false;
}
}

simple code for changing user password in codeigniter

i need a very simple code for changing password for a logged user. i used the following code:
Controller - my_account.php
public function change_password(){
$this->page_handler->consumer_page();
$this->form_validation->set_rules('opassword','Old Password','required|trim|xss_clean|callback_change');
$this->form_validation->set_rules('npassword','New Password','required|min_length[6]|max_length[32]');
$this->form_validation->set_rules('cpassword','Confirm Password','required|matches[npassword]');
if($this->form_validation->run()!=true) {
$this->load->view("passwordchange");
}
else {
$sql = $this->db->select("*")->from("consumer")->where("login", $this->session->userdata("login"))->get();
foreach ($sql->result()as $info) {
$db_password = $info ->password;
$login = $info ->login;
}
if(md5($this->input->post("opassword"))==$db_password) {
$fixed_pw = md5(mysql_real_escape_string($this->input->post("npassword")));
$update = $this->db->query("UPDATE 'consumer' SET 'password' = '$fixed_pw' where 'login' ='$login'") or die(mysql_error());
$this->session->set_flashdata("notification","Password has been updated!");
redirect("MyPage","refresh");
}
else {
echo "Password is incorrect!";
$this->load->view("passwordchange");
}
}
}
Model - page_handler.php
Class Page_handler extends CI_Model{
public function isLoggedIn(){
return $this->session->userdata("Logged_in");
}
public function consumer_page(){
if($this->isLoggedIn()) {
return TRUE;
}
}
}
I am getting error message...
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: db_password
Filename: controllers/my_account.php
Line Number: 23
Password is incorrect!
Where can i be wrong?
It is better to define two methods in your controller.
First :
function check_old_passwd($pass){
//for set custom validation message
$this->form_validation->set_message('check_old_passwd', 'your custom message');
//{check in db...}
if(true){
return true;
}
return false
}
Second :
function is_newpasswd_correct($newpass){
//for set custom validation message
$this->form_validation->set_message('is_newpasswd_correct', 'your custom message');
//check if new password is in your site terms
//not smaller than 4 digits etc.
if(true){
return true;
}
return false;
}
Then use callback in your validation rules :
$this->form_validation->set_rules('oldpass', 'Old Password', 'required|trim|callback_check_old_passwd');
$this->form_validation->set_rules('newpass', 'New Password', 'required|trim|callback_is_newpasswd_correct');
Hope it will helps you

Adding custom callback to Codeigniter Form Validation

I want to limit my registration to emails with #mywork.com I made the following in My_Form_validation.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
I use it as follows. I use CI rules for username and password and it works, for email it accepts any email address. Any I appreciate any help.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
The problem with creating a callback directly in the controller is that it is now accessible in the url by calling http://localhost/yourapp/yourcontroller/yourcallback which isn't desirable. There is a more modular approach that tucks your validation rules away into configuration files. I recommend:
Your controller:
<?php
class Your_Controller extends CI_Controller{
function submit_signup(){
$this->load->library('form_validation');
if(!$this->form_validation->run('submit_signup')){
//error
}
else{
$p = $this->input->post();
//insert $p into database....
}
}
}
application/config/form_validation.php:
<?php
$config = array
(
//this array key matches what you passed into run()
'submit_signup' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[255]|valid_email|belongstowork'
)
/*
,
array(
...
)
*/
)
//you would add more run() routines here, for separate form submissions.
);
application/libraries/MY_Form_validation.php:
<?php
class MY_Form_validation extends CI_Form_validation{
function __construct($config = array()){
parent::__construct($config);
}
function belongstowork($email){
$endsWith = "#mywork.com";
//see: http://stackoverflow.com/a/619725/568884
return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
}
}
application/language/english/form_validation_lang.php:
Add: $lang['belongstowork'] = "Sorry, the email must belong to work.";
Are you need validation something like this in a Codeigniter callback function?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '#mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
A correction to Jordan's answer, the language file that you need to edit should be located in
system/language/english/form_validation_lang.php
not application/.../form_validation_lang.php. If you create the new file under the application path with the same name, it will overwrite the original in the system path. Thus you will lose all the usage of the original filters.

Categories