Validation of an API in codeigniter not working properly - php

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

Related

CI3 / Validation always returns false upon initial load

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

Get multiple values of checkbox in codeigniter

I am currently doing a project. I have a checkbox( where the user will choose type of services provided by the company). When I try to post the service that was selected(for example 2 services is checked) in my controller, I am only getting one service. The question is how can I get the multiple values in my checkbox?
Note: I also tried to use foreach within my controller, I am getting some error like "Invalid argument supplied for foreach()".
View
<label>Desired Service</label> <br>
<?php foreach($services as $s):?>
<label><input type="checkbox" name="service_name[]" value="<?= $s->service_name?>"><?= $s->service_name?></label>
<br>
<?php endforeach?>
Controller
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('full_name', 'Fullname', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('zip_code', 'Zip Code', 'numeric|required');
$this->form_validation->set_rules('province', 'Province', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('service_name', 'Service', 'required');
if ($this->form_validation->run() == FALSE) {
$this->index();
}
else {
$service_name = implode(', ', $_POST['service_name']);
$event = array(
'full_name' => $this->input->post('full_name'),
'email' => $this->input->post('email'),
'contact' => $this->input->post('contact'),
'address' => $this->input->post('address'),
'zip_code' => $this->input->post('zip_code'),
'state_province' => $this->input->post('province'),
'date' => $this->input->post('date'),
'service' => $service_name
);
$this->EventModel->add_event($event);
echo "<script>
window.alert('Your Desired Date is being Proccessed!');
location.href = '".site_url('/')."';
</script>";
}
Change from
$service_name = $_POST['service_name'];
foreach($service_name as $key =>$value)
{
echo $value;
}
die;
to
$service_name = implode(',',$_POST['service_name']);
echo $service_name;
I hope it will solve your problem
if (!empty($this->input->post('service_name'))) {
foreach ($this->input->post('service_name') as $key => $val) {
$data[] = array(
'service_name' => $_POST['service_name'][$key]
);
}
foreach ($data as $item) {
echo $item['service_name'];
}
Try:
$service_name = $this->input->post('service_name');
for($i=0;$i < count($service_name);$i++){
echo $service_name[$i];
}

couldn't insert data in codeigniter

i couldn't insert data to database. i don't know where the problem but when i var_dump($this->mberita->get_berita()); the result is array(0){}. I am a newbie in Codeigniter and couldn't really figure out how to solve this.
model
function get_berita()
{
$this->db->order_by('id_berita','asc');
$data = $this->db->get('berita_ukm');
return $data->result();
}
//untuk menambah berita
function insert_berita($data)
{
$data = array(
'id_berita' => $this->input->post('id_berita'),
'tanggal' => $this->input->post('tanggal'),
'judul_berita' => $this->input->post('judul_berita'),
'content' => $this->input->post('content')
);
$this->db->insert('berita_ukm', $data);
}
function validate_berita()
{
$this->form_validation->set_rules('id_berita', 'Id Berita', 'required|numeric');
$this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == TRUE) {
return TRUE;
}
}
controller
function tambah_berita()
{
if ($this->mberita->validate_berita() == TRUE) {
$this->mberita->insert_berita();
redirect('admin/berita/tambah_berita');
}
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/berita/tambah_berita', '', true);
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
Please help me what to do. Thank you.
<?php
#in controller page#
// notes : you should make validation in controller page
if ($this->input->post('send')){ //request submit
// make form validation
$this->form_validation->set_rules('id_berita', 'Id Berita', 'required|numeric');
$this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == TRUE) {
// request data then put in array
$data = array(
'id_berita' => $this->input->post('id_berita'),
'tanggal' => $this->input->post('tanggal'),
'judul_berita' => $this->input->post('judul_berita'),
'content' => $this->input->post('content')
);
$this->mberita->insert_berita($data);
}
}
//model page
function insert_berita($data)
{
$this->db->insert('berita_ukm', $data);
}

Ion Auth & Codeigniter: Looping redirect when new user login

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

CodeIgniter CAPTCHA validation

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

Categories