I have created some form for inserting data into database and for checking if the data was sent from human I have used CAPTCHA which is already integrated to CI.
This is my controller:
$checkrules = array(
'img_path' => realpath(APPPATH . '../upload/checking/img') . '/',
'img_url' => base_url() . 'upload/checking/img/',
'font_path' => realpath(APPPATH . '../upload/checking/font.ttf'),
'img_width' => 150,
'img_height' => 30,
'expiration' => 7200
);
$check = create_captcha($checkrules);
$data['checkimg'] = $check['image'];
$this->form_validation->set_rules('name', 'Name', 'required|max_length[40]|xss_clean');
$this->form_validation->set_rules('email', 'E-mail', 'required|valid_email|xss_clean');
$this->form_validation->set_rules('website', 'Website', 'max_length[80]|prep_url|xss_clean');
$this->form_validation->set_rules('comment', 'Comment', 'required|xss_clean');
$this->form_validation->set_rules('check', 'Check', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('cms/theme', $data);
}
else
{
echo "success";
$this->load->view('cms/theme', $data);
}
My question now is what's the best way to validate CAPTCHA?
1.) Creating callback, which I have already done, but there was problem because when I send form is error with new CAPTCHA code.
2.) Inserting CAPTCHA's code into database and check from it. Problem is because there will be a lot of loading database and it will be very busy.
And second question. Is this CAPTCHA saving only .jpg pictures in folder or it can be any other format there? (I'm asking this because I want to delete this captcha's after they are used.)
* Example of captcha validation without database useage
* Instead of it used session to store captcha value
* The images will be deleted after the use
public function index()
{
$this->load->helper(array('form', 'url','captcha'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$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');
$this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha');
if($this->form_validation->run() == FALSE)
{
$original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$original_string = implode("", $original_string);
$captcha = substr(str_shuffle($original_string), 0, 6);
//Field validation failed. User redirected to login page
$vals = array(
'word' => $captcha,
'img_path' => './captcha/',
'img_url' => 'http://mycodeignitor.org/captcha/',
'font_path' => BASEPATH.'fonts/texb.ttf',
'img_width' => 150,
'img_height' => 50,
'expiration' => 7200
);
$cap = create_captcha($vals);
$data['image'] = $cap['image'];
if(file_exists(BASEPATH."../captcha/".$this->session->userdata['image']))
unlink(BASEPATH."../captcha/".$this->session->userdata['image']);
$this->session->set_userdata(array('captcha'=>$captcha, 'image' => $cap['time'].'.jpg'));
$this->load->view('index_index',$data);
}
else
{
if(file_exists(BASEPATH."../captcha/".$this->session->userdata['image']))
unlink(BASEPATH."../captcha/".$this->session->userdata['image']);
$this->session->unset_userdata('captcha');
$this->session->unset_userdata('image');
redirect('home', 'refresh');
}
}
public function validate_captcha(){
if($this->input->post('captcha') != $this->session->userdata['captcha'])
{
$this->form_validation->set_message('validate_captcha', 'Wrong captcha code, hmm are you the Terminator?');
return false;
}else{
return true;
}
}
I suggest you to use recaptcha which is easy to implement in codeigniter: http://codeigniter.com/wiki/ReCAPTCHA
Related
I do not understand why upon load the validation always returns false. Here is part of my controller:
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
Here is my validation config from mh_blog_validate:
$config['validate_blog_update'] = array(
'title' => array(
'field' => 'title',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]|callback_is_slug_unique_on_update[]',
'errors' => array(
'required' => 'The title cannot be blank.',
'min_length' => 'The title must be 5 charaters or more.',
'is_unique' => 'The title must be unique.',
'is_slug_unique_on_update' => 'The new title needs to be unique'
),
),
'body' => array(
'field' => 'body',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]',
'errors' => array(
'required' => 'The body cannot be blank',
'min_length' => 'The body must be 5 charaters or more.',
)
),
); // end validate_blog_create
This is the callback function I use in the validate:
function is_slug_unique_on_update() {
$new_slug = url_title($this->input->post('title'));
if ( $new_slug == $this->input->post('slug')) {
// no change in slug so update
// echo "no change in title";
return TRUE;
} elseif ( $new_slug !== $this->input->post('slug')) {
// new slug
$result = $this->Blog_model->is_slug_unique_on_update($new_slug);
return $result; // returns FALSE if the title is not unique
}
}
The output I receive in the view is "Warning - " and this is placed in the view:
if (isset($this->data['alert']){
echo $this->data['alert'];
}
I was expecting the validation not to produce an error because I have not submitted the form. It runs the validation maybe(?) even when I have not submitted the form I think.
+++ new edit +++
Added code below that works and wish to know why mine code doesn't. I thought my code follows the same pattern, no?
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
}
The problem is you are setting $this->data['alert'] values, whether the form is submitting data or not. Of course you could prevent this variable assignment by adding conditional so it will set only when there are any $_POST data is submitted :
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
if ($_POST)
{
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
}
I am writing an API in codeigniter. I am validating the fields it has with codeigniter built in function but somehow it's not working as it should.
public function check_validation()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$firstname = mysql_real_escape_string($this->input->post('firstname'));
$lastname = mysql_real_escape_string($this->input->post('lastname'));
$email = mysql_real_escape_string($this->input->post('email'));*/
//$firstname = 'Numaan';
//$lastname = 'sheikh';
//$email = 'test#test.com';
$this->form_validation->set_rules('firstname', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$finalResult = array('code' => 100,
'msg'=>'Field Emsdsdspty.',
'data' => array()
);
}
else
{
$finalResult = array('code' => 100,
'msg'=>'Validation Successful.',
'data' => array()
);
}
echo json_encode($finalResult);
}
I am trying to get the posted values but it is not working properly.then i also tried to assign the values to the variables and then passed through the validation it also did not work.
Try this (i not testing)
function check_validation()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
//default result
$finalResult = array('code' => 500, 'msg' => 'Unknow Error', 'data' => array());
if($this->input->post()) {
//set validaton
$this->form_validation->set_rules('firstname', 'Username', 'trim|strip_tags|required');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|strip_tags|required');
$this->form_validation->set_rules('email', 'Email', 'trim|strip_tags|required');
//check form
if($this->form_validation->run() == TRUE) {
$finalResult = array('code' => 200, 'msg' => 'Success', 'data' => array());
}else {
$finalResult = array('code' => 400, 'msg' => validation_errors(), 'data' => array());
}
}
echo json_encode($finalResult);
}
ps. api status code: http://www.restapitutorial.com/httpstatuscodes.html
Am a new user to CodeIgniter, have looked at other posts and the answers given sadly don't solve this issue.
Am using a form to create records (also uploads image file and creates link to image as field in db) This all works. I am now trying to edit a particular record. I have a view with the form and this works and is pre-filled from the db using $id = $this->uri->segment(3) to grab the correct record - this all works.
Where it fails is then in updating the record.
My controller...
function edit_stock_vehicle_record()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('make', 'Make', 'trim|required');
$this->form_validation->set_rules('model', 'Model', 'trim|required');
$this->form_validation->set_rules('fuel', 'Fuel Type', 'trim|required');
$this->form_validation->set_rules('enginesize', 'Engine Size', 'trim|required');
$this->form_validation->set_rules('trans', 'Transmission', 'trim|required');
$this->form_validation->set_rules('reg_no', 'Registration Number', 'trim|required');
$this->form_validation->set_rules('year', 'Year', 'trim|required');
$this->form_validation->set_rules('colour', 'Colour', 'trim|required');
$this->form_validation->set_rules('mileage', 'Mileage', 'trim|required');
$this->form_validation->set_rules('long_desc', 'Description', 'trim|required');
$this->form_validation->set_rules('purchase_price', 'Purchase Price', 'trim|required');
$this->form_validation->set_rules('sale_price', 'Sale Price', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content'] = 'vehicle_display2';
$this->load->view('includes/template', $data);
}
else
{
$this->load->model('manage_model');
if($query = $this->manage_model->edit_stock_vehicle_record())
{
$data['main_content'] = 'vehicle_added';
$this->load->view('includes/template', $data);
}
else
{
$data['main_content'] = 'add_vehicle4';
$this->load->view('includes/template', $data);
}
}
}
My model....
function edit_stock_vehicle_record()
{
$this->load->helper('array');
$this->load->helper('html');
$id = $this->uri->segment(3);
$config['upload_path'] = 'c:/wamp/www/honest/images';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['main_content'] = 'imageupload';
$this->load->view('includes/template', $data);
echo "FAILED";
}
else
{
$image_data = $this->upload->data();
$vehicle_update_data = array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->load->helper('url');
$id = $this->uri->segment(3);
$update = $this->db->update('stock_vehicles', $vehicle_update_data, array('id' => $id));
return $update;
}
}
I have also tried versions using....
$this->db->where('id', $id);
$this->db->update('stock_vehicles', $vehicle_update_data);
But this also fails, it seems as if the $id is not being recognized correctly.
If I remove the above and just use $this->db->update('stock_vehicles', $vehicle_update_data); it does indeed update every record in the db (doh!) Fortunately there was no 'real' data in there when I discovered this!
Not sure why it is not picking up the $id - all input gratefully received.
Cheers,
DP.
I have a view with the form and this works and is pre-filled from the
db using $id = $this->uri->segment(3) to grab the correct record -
this all works.
Do NOT do this for the form update. Just include the id in a hidden form field. Much easier, safer, etc.
echo form_hidden( 'id', $id );
first you must load the url helper in your Controller:
$this->load->helper('url');
then you should try this code:
$id = $this->uri->segment(3);
$vehicle_update_data =array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->db->WHERE('id',$id)->update('your_table',$vehicle_update_data);
return true;
hey guys im trying to validate a captcha code in codeigniter. is there an easy way to validate the captcha? here is my code and it is not working because everytime it loads the page it will call a new captcha which will replace the word in the session.
public function index() {
$originalString = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$originalString = implode("", $originalString);
$captcha = substr(str_shuffle($originalString), 0, 6);
$vals = array(
'word' => $captcha,
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => 150,
'img_height' => 50,
'expiration' => 7200 );
$cap = create_captcha($vals);
$captchaImage = $cap['image'];
$this->session->set_userdata($cap);
if(isset($_POST['register'])) {
$this->form_validation->set_rules('firstName', 'First Name', 'required');
$this->form_validation->set_rules('lastName', 'Last Name', 'required');
$this->form_validation->set_rules('emailAddress', 'Email', 'required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[6]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[confirm-password]|min_length[6]');
$this->form_validation->set_rules('confirm-password', 'Password Confirm', 'required');
$this->form_validation->set_rules('secretquestion', 'Secret Question', 'required');
$this->form_validation->set_rules('answer', 'Answer', 'required');
$this->form_validation->set_rules('inputCode', 'Captcha', 'required|');
if ($this->form_validation->run() == TRUE) {
$user = $this->Account_Model->validation($_POST['username']);
if($_POST['inputCode'] != $this->session->userdata('word')){
echo $_POST['inputCode'] .' = ' .$this->session->userdata('word');
$this->_error = 'Code does not match the image';
} else {
if(empty($user)) {
$this->load->library('upload');
$accountId = $this->Account_Model->addUser($_POST);
$config['upload_path'] = './assets/uploads/avatars';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $_POST['username'];
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('avatar'))
{
$error = array('error' => $this->upload->display_errors());
}
if($accountId){
$this->_body = array(
'username' => $_POST['username'],
'email' => $_POST['emailAddress'],
'secretQuestion' => $_POST['secretquestion'],
'answer' => $_POST['answer'],
'captchaImage' => $captchaImage
);
$this->_template = 'register_success';
return $this->_renderPage();
}
}
}
}
}
$this->_body = array(
'secretQuestions' => $this->questions,
'captchaImage' => $captchaImage,
'error' => $this->_error
);
return $this->_renderPage();
}
is there a better way to do this??.. please help.. tnx in advanced..
Maybe the easiest way would be to not create a new captcha once the user submits the form, or at least not update the session.
if(!$_POST){
$this->session->set_userdata($cap);
}
I am a frequent user of Codeigniter and it has come to the point where i've had to start looking at a library for login/forgot password so i decided to use Ion Auth.
I set this up - works fine, tried the admin account that is already set up with it and it's fine.
Now when i login as the admin and then create a new user, the data is added to the database and the page redirects from "create-user" to the welcome page. But if i logout and login with these new details, the page goes blank and the reload bar goes crazy! The url bar looks like it goes to the welcome page if that makes sense but nothing loads.
I've also checked my console on firebug and the php log error and nothing at all.
I've checked my database and when the user has been added, the password has been hashed but in the salt column it is classed as NULL whereas the default account already set up has a hash code? - could this be something to do with it?
EDIT: I've now altered the code but this still didn't worked when it wasn't touched so only edits in code are removal of tables and in the auth controller the functions are login, create_user and logout.
And when the admin#admin.com user logs in it loads the page fine just other"new" accounts..
Thanks!
//log the user in
function login() {
$this->data['title'] = "Login";
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true) {
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}else{
//if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh');
}
}else{
//the user is not logging in so display the login page
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('auth/login', $this->data);
}
}
//log the user out
function logout() {
$this->data['title'] = "Logout";
$logout = $this->ion_auth->logout();
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('auth/login', 'refresh');
}
//create a new user
function create_user() {
$this->data['title'] = "Create User";
$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', 'Password Confirmation', 'required');
if ($this->form_validation->run() == true) {
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = $this->input->post('email');
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name')
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data)) {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/login", 'refresh');
}else{
//display the create user form
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name'),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->_render_page('auth/create_user', $this->data);
}
}
function _render_page($view, $data=null, $render=false) {
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $render);
if (!$render) return $view_html;
}
}
WELCOME PAGE CONTROLLER
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('ion_auth');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->helper('url');
}
public function index() {
if (!$this->ion_auth->logged_in()) {
redirect('auth/login', 'refresh');
}elseif (!$this->ion_auth->is_admin()) {
redirect('/', 'refresh');
}else{
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->_render_page('auth/welcome', $this->data);
}
}
}
RESOLVED: This was a bug with Google Chrome which i've had to update the system and the brwser. Also for storing the SALT i changed some settings in my ion_auth config file
This was a bug with Google Chrome which i've had to update the system and the browser. Also for storing the SALT i changed some settings in my ion_auth config file