How To Make Form Validation Codeigniter? - php

I want to make form validation on codeigniter
this is the code from alternatif.php on controller
class Alternatif extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model("Alternatif_model");
$this->load->model("User_model");
if (!$this->session->userdata('email')) {
redirect('auth');
}
$data['user'] = $this->db->get_where('users', ['email' => $this->session->userdata('email')])->row_array();
}
public function tambahAlternatif()
{
$data['title'] = 'Tambah Alternatif';
$data['user'] = $this->db->get_where('users', ['email' => $this->session->userdata('email')])->row_array();
if ($this->input->post('nambahAlternatif')) {
foreach ($this->input->post() as $key => $value) {
if (strpos($key, "id_aspek_teknik-") !== false) {
$k = str_replace('id_aspek_teknik-', '', $key);
$this->Alternatif_model->tambahNilai($k);
}
}
$this->Alternatif_model->tambahAlternatif();
$this->session->set_flashdata('flash', 'ditambahkan');
redirect('alternatif');
} else {
code
}
}
I want to ask where I can add the form validation on codeigniter?

Add validation on Controller like:
public function tambahAlternatif()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
if ($this->form_validation->run() == FALSE)
{
// this block working when get error
$this->load->view('myform');
}
else
{ // when success
$this->load->view('formsuccess');
}
}
check official documentation here
Use this code on your view file (where your form was submitted) <?php echo validation_errors(); ?> it return your errors
Note: this validation errors on view file only work for PHP version <=7.3. PHP v8 not supported

Related

Unable to view Form page in CodeIgniter facing Error

This is my home.php file in this controller I am facing Fatal error: Uncaught ArgumentCountError:
I have also attached a screenshot, In this screenshot error mentioned, You can easily understand the error through this screenshot, I am newbie in CodeIgniter.
[
I upload only my controller related file.
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('select');
$this->load->helper(array('form', 'url', 'html'));
$this->load->library(array('form_validation', 'session'));
}
function records() {
$ytl['dta'] = $this->users->datas();
//$this->load->view('info',$ytl);
//echo "<pre>controller";print_r($ytl);
}
function primezone() {
$ytl['dta'] = $this->users->datas();
echo "<pre>controller";
print_r($ytl);
}
function form($id) {
//die($id);
if ($this->input->post()) {
//echo"<pre>";print_r( $this->input->post());die;
$this->form_validation->set_rules('fname', 'First Name', 'required|min_length[5]');
$this->form_validation->set_rules('lname', 'Last Name', 'required|callback_check_picture[lname]');
//$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('mobile', 'Mobile Number', 'required|callback_valid_phone_number[mobile]');
$this->form_validation->set_error_delimiters('<h1 class="error">', '</h1>');
if ($this->form_validation->run() == TRUE) {
$data = [
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'message' => $this->input->post('message'),
];
if (empty($id)) {
$ytl = $this->select->insertdata($data);
} else {
$ytl = $this->select->updatedata($data, $id);
}
if ($ytl) {
$this->session->set_flashdata('message', 'Successfully Added.');
redirect('home');
}
} else {
//$this->load->view('form');
}
}
$ytl['dta'] = $this->select->getDataById($id);
//echo "<pre>";print_r($ytl);die;
$this->load->view('form', $ytl);
}
public function check_picture($a) {
if ( ! is_numeric($a)) {
return TRUE;
} else {
$this->form_validation->set_message('check_picture', 'Please enter only char value');
return FALSE;
}
}
function valid_phone_number($value) {
$value = strlen($value);
//echo $value;die;
if ($value == 10) {
return TRUE;
} else {
$this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}
return FALSE;
}
}
public function index() {
//load the database
//$this->load->database();
//load the model
$this->load->model('select');
//load the method of model
$data['h'] = $this->select->select();
//return the data in view
$this->load->view('fetch_view', $data);
}
public function delete() {
$this->load->model('select');
$id = $this->input->get('id');
if ($this->select->deleteuser($id)) {
$data['data'] = $this->select->getuser();
$this->load->view('fetch_view', $data);
}
}
}
The error you have mention is normally came when there is mismatch in param mention in function and the passing ones.
According to your code
public function form($id)
$id is required and you are not passing that.
So change your code to
public function form($id=null)
Set default id value in your controller function like
function form($id = null){
....
}

CodeIgniter - Unable to access an error message corresponding to your field name

I'm creating a library to add new users.
class Register
{
private $CI;
public function add_new_user()
{
$CI =& get_instance();
$CI->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');
if ($CI->form_validation->run() == TRUE)
{
$email = $_POST['email'];
$insert_data = array('email' => $email);
$CI->new_data->add_user($insert_data);
}
}
private function is_email_exist($email)
{
$CI =& get_instance();
$email_result = '';
$query = $CI->check->find_email($email);
foreach ($query->result_array() as $row)
{
$email_result = $row['email'];
}
if ($email_result == $email)
{
$CI->form_validation->set_message('is_email_exist', 'Such email already exist!');
return FALSE;
}
else
{
return TRUE;
}
}
}
I add form_validation and models check, new_data to the autoload. When I submit a form instead of an error (if it should be there) I get Unable to access an error message corresponding to your field name Username.(is_username_exist). What should i do to get right error?
Codeigniter form validation is for the controller so when submit form it goes there
https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller
Controller Way
<?php
class Register extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('some_model');
}
public function index() {
$this->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');
if ($this->form_validation->run()) {
$insert_data = array(
'email' => $this->input->post('email')
);
$this->some_model->new_data->add_user($insert_data);
}
$data['title'] = 'Welcome To Codeigniter';
$this->load->view('header', $data);
$this->load->view('someview', $data);
$this->load->view('footer');
}
// Check user email
public function is_email_exist() {
// Single input check
$this->db->where('email', $this->input->post('email'));
$query = $this->db->get('user');
// If user email greater than 0
if ($query->num_rows() > 0) {
return TRUE;
} else {
$this->form_validation->set_message('is_email_exist', 'Such email already exist!');
return FALSE;
}
}
}
replace 'is_email_exist' to __FUNCTION__ work for me,
https://stackoverflow.com/a/38950446/2420302

User login status activation check in codeigniter?

I'm new in Codeigniter. I have a login system where user with status is 0 can't do login yet and where user with status 1 can login. I might be have a mistake in my code. So, i hope you can find where is my mistake and help me to make it right. here's my code.
My Controller
public function login() {
$this->form_validation->set_rules('no', 'No', 'required|min_length[10]|max_length[16]|integer');
$this->form_validation->set_rules('password', 'password', 'required|md5|xss_clean');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if($this->form_validation->run()== FALSE) {
$this->load->view('v_login');
}else{
$no = $this->input->post('no');
$password = $this->input->post('password');
$cek = $this->m_user->ambilPengguna($no, $password);
$status = $this->m_user->ambilStatus($no); //HERE'S THE PROBLEM
if($cek->num_rows()<> 0 && $status == '1') { //HERE'S TOO, IT WON'T CHECK THE STATUS.
$this->session->set_userdata('isLogin', TRUE);
$this->session->set_userdata('data_user',$cek->row());
redirect('c_belajar');
}else {
echo " <script>
alert('Login failed! call the administrator to activate your account');
history.go(-1);
</script>";
}
}
}
My Model
public function ambilPengguna($no, $password) {
$this->db->select('*');
$this->db->from('tb_user');
$this->db->where('no_id', $no);
$this->db->where('password', $password);
$query = $this->db->get();
return $query;
}
public function ambilStatus($no){
$this->db->select('status');
$this->db->from('tb_user');
$this->db->where('no_id', $no);
$query = $this->db->get();
return $query;
}
There's a mistake on controller. Please help me.
Alright! May I suggest a little code restructure
Controller
class YourController extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('login_model');
$this->load->library('form_validation');
}
public function login()
{
if($_POST)
{
$config=array(
array(
'field' => 'no',
'label' => 'Number',
'rules' => 'trim|required',
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required',
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()==false)
{
$data['errors']=validation_errors();
$this->load->view('login',$data);
}
else
{
$check=$this->login_model->checkUser($_POST); // you can use xss clean here filter post data
if(!$check)
{
$data['errors']='Invalid Password';
$this->load->view('login',$data);
}
elseif($check==1)
{
$data['errors']='Your account status is not active yet, Please contact Administrator';
$this->load->view('login',$data);
}
else
{
$this->session->set_uerdata($check);
redirect(base_url().'dashboard');
}
}
}
else
{
$this->load->view('login');
}
}
}
Model
class login_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function checkUser($data)
{
$st=$this->db->select('*')
->from('tbl_user')
->Where('no_id', $data['no'])
->where('password', $data['password'])
->get()->result_array();// you can use row()
if(count($st)>0)
{
if($st[0]['status']==0){
return 1;
}
else
{
return $st[0];
}
}
else
{
return false;
}
}
}
Try this, this working in my project..
Your Model
public function ambilStatus(){
$this->db->where('no_id', $this->input->post('your input name'));
$query = $this->db->get($this->db->dbprefix . 'tb_user');
$ret = $query->row();
return $ret->account_status;
}
And Your Controller
$status = $this->m_user->ambilStatus();
if($status && $cek->num_rows() == 1 ) {

Codeigniter - How to avoid user entering logged page without login?

I have Controller called login.php that will take login credentials, if true user will be directed to a method profile() in another controller called page.php.
In that profile() method only contain a command to load the view of user's profile.
So the route is like this:
Home->login->profie
But when I try to bypass the login process via url like this
Home->profile
The system still accept that. How can I make a rule that a user can't open profile if they're not logged in?
Here's the Controller:
page.php
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
login.php
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
?>
Can anyone please help me how to fix this?
Thank you.
Add a constructor to every applicable controller.
Let the constructor check if the user is logged in, possibly by checking if a particular session exists. If it doesn't redirect to the login page.
Something like below
function __construct(){
parent::__construct();
if(!$this->session->userdata('userid')){
redirect('user/login');
}
}
use this at the top of the page you don't want it accessed when not logged in (supposing you've already set session data)
<?php if (!isset($_SESSION['username'])) {
redirect(base_url());
} ?>
Before showing that page, you should check whether that session exist or not, like if($this->session->userdata('username')). If exists, show that page, if not show any warning.
You can try
if ($this->session->userdata('login') == true) {
redirect('controller');
}
Login Controller
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
if ($this->session->userdata('login') == true) {
redirect('controller');
}
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
Couple things I noticed also in Codeigniter 3 + versions the first letter must only be upper case on FILENAME and Controller Class
Also you don't need to close the controllers and model with ?> https://www.codeigniter.com/user_guide/general/styleguide.html#php-closing-tag
If for example you don't want the user to enter a function without login, you could check the session in the constructor of the class.
If it's only for a specific function, you could just also check the session in the function directly.
Create a helper file login_helper.php
function check_login( $session ) {
$CI =& get_instance();
$CI->load->helper('url');
if(!$session->userdata('login')){
redirect(base_url());
}
}
Now use this helper function in controllers where login is mandatory
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
check_login();
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
Note: add login_helper in autoload.php in config folder.
$autoload['helper'] = array('login','url','cookie');
if($this->session->userdata('logged_in') == FALSE) {
$this->session->set_flashdata('error','<p class="alert alert-danger">Please login to view this page.</p>');
redirect('login_c');
exit;
}

parse error in controller file

i made a controller name of user.php i test complete project on local host it works fine but when i upload online on website it shows error , i submit the form then form load controller called user.php and error on the first line its called parse error i check but still the same will you please suggest.
<?php
class User extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
public function create_user()
{
// field name, error message, validation rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('city', 'City', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('ar_signup');
}
else
{
$this->load->model('Users_model');
if($this->input->post("language")=="ar")
{
$this->load->view('ar_thanks');
}
else
{
$this->load->view('en_thanks');
}
if($query = $this->Users_model->create_member())
{
$this->load->view('ar_thanks');
}
}
}
}
Please format your code and use IDE. And you will not have these errors. Your formatted code:
<?php
class User extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
public function create_user()
{
// field name, error message, validation rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('city', 'City', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->load->view('ar_signup');
} else {
$this->load->model('Users_model');
if($this->input->post("language")=="ar") {
$this->load->view('ar_thanks');
} else {
$this->load->view('en_thanks');
}
if($query = $this->Users_model->create_member()) {
$this->load->view('ar_thanks');
}
}
}
}

Categories