Codeigniter 3 - problem with submitting form values to controller - php

I am a beginner of Codeigniter 3. I am trying to submit two form values in a view. Here is the code:
<?php
class User extends CI_Controller{
public function __construct(){
parent::__construct();
if(!isset($_SESSION['user_logged'])){
redirect("auth/login","refresh");
}
}
public function profile(){
$this->load->view('profile');
}
public function members(){
if ($this->input->post('promote')!==FALSE){
$this->form_validation->set_rules('username','Userpromote','required');
if($this->form_validation->run() == TRUE){
$data = array(
'subadmin' => $_POST['username']
);
$this->db->insert('sub', $data);
redirect("user/members", "refresh");
}
} elseif ($this->input->post('demote')!==FALSE){
$this->form_validation->set_rules('subdemote','Userdemote','required');
if($this->form_validation->run() == TRUE){
$data2 = $_POST['subdemote'];
$this->db->delete('sub', array('subadmin' => $data2 ));
redirect("user/members", "refresh");
}
}
$this->load->view('members');
}
public function products(){
$this->load->view('products');
}
}
But problem is, only 'promote' part works, but the 'demote' portion doesn't. If i erase the 'promote' part, the 'demote' park work fine. Could you please tell me what i'm doing wrong ?

It seems to me that you have a logic problem. You have the 'demote' code on a else if block, which means once the if statement is satisfied the else if won't be reached at all. Also you are using redirect on the end of the statements, which means you'll be redirected on that moment and the rest of the script won't be executed. You might try two sepparate if's like this:
public function members(){
if ($this->input->post('promote')!==FALSE){
$this->form_validation->set_rules('username','Userpromote','required');
if($this->form_validation->run() == TRUE){
$data = array(
'subadmin' => $_POST['username']
);
$this->db->insert('sub', $data);
//redirect("user/members", "refresh");
}
}
if ($this->input->post('demote')!==FALSE){
$this->form_validation->set_rules('subdemote','Userdemote','required');
if($this->form_validation->run() == TRUE){
$data2 = $_POST['subdemote'];
$this->db->delete('sub', array('subadmin' => $data2 ));
//redirect("user/members", "refresh");
}
}
$this->load->view('members');
}

Related

I get error when i login to my project and then go back to the base url

I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.

CodeIgniter: 404 Page Not Found ( In Hosting Server )

note : everything going well when I try in Localhost.
So I have a problem when I want to call my do_login controller in my login form.
this is my controller :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Do_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login_model', '', TRUE);
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login_view');
}
else
{
redirect('home', 'refresh');
}
}
public function check_database($password)
{
$email = $this->input->post('email', TRUE);
$result = $this->login_model->check_login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'user_id' => $row->user_id,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Email / Password salah');
return FALSE;
}
}
}
?>
this is my view :
<?php
$attributes = array('class' => 'form-signin', 'id' => 'myform');
echo form_open('do_login', $attributes);
?>
When I try it in Localhost, everything going well and smooth.
But when I try in my web server, everytime I submit the login form, I directed into 404.
Thanks for your help :)
Check your file names Because it happens with me that different case file name was worked on localhost but not on server.
So check it once.

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

How to Update Data in CodeIgniter?

First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.

codeigniter CMS form validation

Firstly Im new to CodeIgniter and MVC.
I am Creating a CMS and coudln't decide which route to take with do I have two applications (front end/CMS) or just create the admin as a controller. I opted for one application and creating the admin via a Controller.
Doing it this way I have ran into a problem with form validation where if it doesn't validate I cant load the form I have to redirect which then means it wont repopulate the unvalidated fields. I use a variable in the 3rd URI segment to determine whether to display a form for inserting a new record, a populated form for editing a record, or a tabled list of all records.
The form posts to /admin/videos/save
function videos()
{
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
$this->load->model('videos_model');
$data['section'] = "Videos";
$data['area'] = "Videos";
$data['mode'] = $this->uri->segment(3, 'create');
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
if ($data['mode'] == 'edit') {
$data['ID'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_videos($data['ID']);
} elseif ($data['mode'] == 'list') {
if ($this->uri->segment(4)) {
$data['filter'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_filtered_videos($data['filter']);
} else {
$data['videos'] = $this->videos_model->get_filtered_videos();
}
} elseif ($data['mode'] == 'save') {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('videoTitle', 'Title', 'required');
$this->form_validation->set_rules('Code', 'Youtube Code', 'required');
if ($this->form_validation->run() === FALSE) {
redirect('/admin/videos');
} else {
$this->videos_model->set_videos();
redirect('/admin/videos/list');
}
}
if ($data['mode'] != "create" && empty($data['videos'])) {
show_404();
}
$this->load->view('admin/templates/head', $data);
$this->load->view('admin/templates/body_navbar', $data);
$this->load->view('admin/videos', $data);
$this->load->view('admin/templates/footer', $data);
}
}
Am I setting about this the wrong way, Should I use two application folders or have 3 controllers for editing/inserting/viewing all. Or is there a solution to my current setup?
I personally haven't used CodeIgniter's form helper nor validation lib, so excuse my ignorance, but is there any particular reason you're not doing this as AJAX post instead?
Am I setting about this the wrong way, Should I use two application
folders or have 3 controllers for editing/inserting/viewing all. Or is
there a solution to my current setup?
Why 3 controllers? You can have a single controller with multiple functions. Honestly, I'd recommend just doing a simple AJAX post on your form and returning some JSON data whether validation passed or not -- no need for redirects.
Something like:
// AJAX
function validateForm() {
$.post('route/to/controller', {"apple": appleValue, "peach": peachValue}, function(data) {
json = $.parseJSON(data);
if (json.success)
alert('Great!');
else
alert('Nope!');
});
//Controller
function validateForm()
{
$data['success'] = ...validation checks...
echo json_encode($data);
}
I have continued to use my one application folder and the entire admin as a controller.
I have solved my form validation and repopulating issue by continuing to redirect back to the form but storing the form fields and errors in a session.
I destroy the error data in the session once viewed but leave the other info intact which allows the user to navigate away and come back and the info will remain. Once the form is validated correctly and information stored in the database it destroys the session data.
function videos()
{
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
$this->load->model('videos_model');
$data['section'] = "Videos";
$data['area'] = "Videos";
$data['mode'] = $this->uri->segment(3, 'create');
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
if ($this->session->userdata('videoTitle'))
$data['videoTitle'] = $this->session->userdata('videoTitle');
if ($this->session->userdata('Code'))
$data['Code'] = $this->session->userdata('Code');
if ($this->session->userdata('videoTitle'))
$data['description'] = $this->session->userdata('description');
if ($this->session->userdata('errors')){
$data['errors'] = $this->session->userdata('errors');
$this->session->unset_userdata('errors');
}
if ($data['mode'] == 'edit') {
$data['ID'] = $this->uri->segment(4);
$video_data = $this->videos_model->get_videos($data['ID']);
$data['videoTitle'] = $video_data['videoTitle'];
$data['Code'] = $video_data['blipCode'];
$data['description'] = $video_data['description'];
} elseif ($data['mode'] == 'list') {
if ($this->uri->segment(4)) {
$data['filter'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_filtered_videos($data['filter']);
} else {
$data['videos'] = $this->videos_model->get_filtered_videos();
}
} elseif ($data['mode'] == 'save') {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('videoTitle', 'Title', 'required');
$this->form_validation->set_rules('Code', 'Youtube Code', 'required');
if ($this->form_validation->run() === FALSE) {
$formdata = array(
'videoTitle' => $this->input->post('videoTitle'),
'Code' => $this->input->post('Code'),
'description' => $this->input->post('description'),
'errors' => validation_errors()
);
$this->session->set_userdata($formdata);
redirect('/admin/videos');
} else {
$this->videos_model->set_videos();
$this->session->unset_userdata('videoTitle');
$this->session->unset_userdata('Code');
$this->session->unset_userdata('description');
redirect('/admin/videos/list');
}
}
$this->load->view('admin/templates/head', $data);
$this->load->view('admin/templates/body_navbar', $data);
$this->load->view('admin/videos', $data);
$this->load->view('admin/templates/footer', $data);
}
}

Categories