how to validate the data of ckeditor in CI - php

I need to validate the data of ckeditor. Is there any way to validate it in CodeIgniter? I have tried like this.
In View:
<div class="col-sm-12 col-md-10">
<textarea class="ckeditor" name="desc" id="editor" required><?php echo set_value('desc', ''); ?></textarea>
<span class="error"><?php echo form_error('desc'); ?></span>
</div>
In controller:
$this->form_validation->set_rules('desc', 'Desc', 'required');
if ($this->form_validation->run() == FALSE) {
$this->add_Coachs();
} else {
$rs = $this->functional->insertBlog();
if ($rs == true) {
$this->session->set_flashdata('blog', 'Your Blog Submitted Successfully.Thank You!');
redirect('Wall');
} else {
$this->session->set_flashdata('blog', 'Blog Not Submitted');
redirect('Wall');
}
}
But here it executes the false condition. Can anyone tell me where I'm going wrong? Is there any way to resolve this problem?
Edited :
In model :
public function insertBlog() {
$full_name = $this->session->userdata('first_name') . " " . $this->session->userdata('last_name');
$email = $this->session->userdata('email');
$data = array(
'user_id' => $this->input->post('user_id'),
'full_name' => $full_name,
'email' => $email,
'desc' => $this->input->post('desc'),
'create_date' => date('Y-m-d h:i:s', now()),
'modify_date' => date('Y:m:d h:i:s'),
'start_date' => date('Y:m:d h:i:s'),
'end_date' => date('Y:m:d h:i:s'),
'status' => "Deactive",
'userby' => $this->input->post('user_id')
);
$rs = $this->db->insert('ult_latest_blog', $data);
return $rs;
}

Related

Can't insert checkbox data in sql database ( not stored or null in database ) - using codeigniter

As per question title i can't manage to insert checkbox data into database
Here is my model
public function rules() {
return array(
array( 'field' => '_butype_',
'label' => 'Business Type',
'rules' => 'required|trim|alpha_numeric_spaces|min_length[2]|max_length[50]'),
array( 'field' => '_bumotiv_[]',
'label' => 'Motivation',
'rules' => 'required'),
);
}
public function getById($id){
return $this->db->get_where($this->table, array($this->primary => $id) )->row_array();
}
public function getAll() {
return $this->db->get($this->table)->result_array();
}
public function insert(){
$post = $this->input->post();
if (!empty($post)){
$data = array(
'ginfo_id' => NULL,
'ginfo_butype' => htmlspecialchars($post['_butype_']),
'ginfo_bumotiv' => json_encode($$post['_bumotiv_[]']),
);
$data = $this->security->xss_clean($data);
if($this->db->insert($this->table, $data)){
$response = array(
'status' => 'success',
'message' => 'Success insert data',
);
} else {
$response = array(
'status' => 'error',
'message' => 'Failed insert data',
);
}
} else {
$response = array(
'status' => 'error',
'message' => 'Data not found!',
);
}
return $response;
}
Here is my Controller
public function add(){
$this->form_validation->set_rules($this->M_Ginfo->rules());
if ($this->form_validation->run() === TRUE) {
$this->session->set_flashdata('notif', $this->M_Ginfo->insert());
redirect(site_url('admin/ginfo/add'),'refresh');
} else {
$data['notif'] = $this->M_Auth->notification();
$this->load->view('admin/ginfo/add.php', $data);
}
}
Here is my model
<div class="form-group row">
<label for="_bumotives_[]" class="col-sm-3 col-form-label" style="text-align: left;">What actually motivated you to start your own business? </label>
<div class="col-sm-6">
<input class="form-group" type="checkbox" name="_bumotiv_[]" id="_bumotiv_[]" value="To be independent from working for other people" <?php echo set_checkbox('bumotiv_[]', 'To be independent from working for other people', false); ?>>
<label for="_bumotiv_[]" >To be independent from working for other people. </label>
<br>
<input class="form-group" type="checkbox" name="_bumotiv_[]" id="_bumotiv_[]" value="I have a bright idea that can be commercialised" <?php echo set_checkbox('bumotiv_[]', 'I have a bright idea that can be commercialised', false); ?>>
<label for="_bumotiv_[]" >I have a bright idea that can be commercialised.</label>
<br>
</div>
There are other data that got insert successfully only checkbox is the only form field that has not been submitted to the database
I tried many solution but non worked for me
Any help is appreciated
If non of the checkbox is selected you will not get any result for checkbox.
Check your code for insert query there is an extra $
'ginfo_bumotiv' => json_encode($$post['_bumotiv_[]']),

How to upload image in codeigniter

controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!$this->upload->do_upload('agent_image')) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<?= form_open_multipart('agent/edit/' . $id); ?>
<?php if (!empty($error)): ?>
<div class="alert alert-danger alert-dismissible" role="alert">
<?= $error; ?>
</div>
<?php endif; ?>
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
<button type="submit" class="btn btn-success">Update</button>
<?= form_close(); ?>
Hi I'm developing a image upload module and image path save in database and retrieve.
my Question I want it to edit and update but the my problem is it doesn't delete the old image in folder, but it save and update the new image.
use file helper of codeigniter
$this->load->helper("file");
delete_files($path);
reference link for you is here
Delete using the file name saved in the database, use the PHP unlink(../filename.jpg) and delete from files
Change in Model
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['agent_img_url'] = $data['agent_img_url'];
}
$q = $this->db->where('id',$id)
->get('agent');
$query = $q->row_array();
#unlink("./asset/uploads/".$query['agent_img_url']);
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
if (!$this->upload->do_upload($name)) {
$data = array('msg' => $this->upload->display_errors());
} else {
$data = array('msg' => "success");
$databasea['upload_data'] = $this->upload->data();
$this->load->library('image_lib');
return $databasea['upload_data']['file_name'];
}
return '';

update statement breaking the database

I am trying to figure out what's wrong here, but really not sure. I have a site with users, when a user edits details, it seems to override all other records with those details. This doesn't happen always but sometimes (of course the result is chaos!). Here is the code of update
public function update_edit()
{
/* echo " //// INSIDE UPDATE EDIT "; */
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|min_length[6]|max_length[100]');
//check that there are no form validation errors
if($this->form_validation->run() == FALSE)
{
/* echo " //// INSIDE FORM VALIDATION"; */
if(($this->session->userdata('username')!=""))
{
/* echo " //// INSIDE SESSION VALIDATION"; */
$data = array();
$data = $this->profileModel->load_user_editable_data($this->session->userdata('username'));
$this->load->view('layout/header');
$this->load->view('profile_edit', $data);
$this->load->view('layout/footer');
//$this->load->view('thankyou');
}else{
//$this->load->view('login');
$this->login();
}
}else{
$complete = $this->profileModel->update_profile($this->session->userdata('username'));
if($complete == 1)
{
$this->load->view('layout/header');
$this->load->view('update_complete');
$this->load->view('layout/footer');
}
}
}
This is the model code:
public function update_profile($username)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$fullImagePath;
if (isset($_FILES['profilepic']) && !empty($_FILES['profilepic']['name']))
{
if ($this->upload->do_upload('profilepic'))
{
$upload_data = $this->upload->data();
$fullImagePath = '/uploads/' . $upload_data['file_name'];
}
}else{
$fullImagePath = $this->session->userdata('profilepic');
}
$data = array(
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'telephone' => $this->input->post('telephone'),
'about' => $this->input->post('about'),
'address' => $this->input->post('address'),
'profilepic' => $fullImagePath,
);
$this->db->where('username', $username);
$this->db->update('free_user_members', $data);
return 1;
}
and this is the form:
<div class="content_container">
<div id="rt-main" class="mb8-sa4">
<div class="rt-container">
<div class="rt-grid-12">
<div dir="rtl" class="homecontent">
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('profile/update_edit'); ?>
<? $this->session->set_userdata('profilepic', $profilepic); ?>
<h5>الاسم الكامل</h5>
<? $data = array(
'name' => 'fullname',
'id' => 'round_input',
'value' => $fullname,
);
echo form_input($data); ?>
<h5>الايميل</h5>
<? $data = array(
'name' => 'email',
'id' => 'round_input',
'value' => $email,
'size' => '70'
);
echo form_input($data); ?>
<h5>الجوال</h5>
<? $data = array(
'name' => 'mobile',
'id' => 'round_input',
'value' => $mobile,
);
echo form_input($data); ?>
<h5>هاتف</h5>
<? $data = array(
'name' => 'telephone',
'id' => 'round_input',
'value' => $telephone,
);
echo form_input($data); ?>
<h5>العنوان</h5>
<? $data = array(
'name' => 'address',
'id' => 'round_input',
'value' => $address,
'size' => '70'
);
echo form_input($data); ?>
<h5>نبذة عني</h5>
<? $data = array(
'name' => 'about',
'id' => 'round_input',
'value' => $about,
'rows' => '3',
'cols' => '40',
);
echo form_textarea($data); ?>
<h5>الصورة الشخصية</h5>
<img width="300" height="300" src="<? echo $profilepic; ?>" />
<h5>إختيار صورة جديدة</h5>
<?
$data = array(
'name' => 'profilepic',
'id' => 'profilepic',
);
echo form_upload($data);
?>
<div><input type="submit" value="احفظ التغييرات" /></div>
</form>
</div>
<p> </p>
</div>
</div>
<div class="clear"></div>
</div>
</div>
will really appreciate it if someone tells me what I am doing that could lead to that chaos every now and then.
Regards,
You have to add code to check that username in the session exists.
If the session times out, codeigniter will return FALSE.
Querying MySQL on username = false will return all rows.

Error updating the user settings in ionauth : "This form post did not pass our security checks."

I am using Ionauth library in codeigniter and edited edit_user() method in Auth controller to enable individual user updating his/her own user settings. So when a logged in user goes to : siteurl/auth/edit_user it shows the user settings just fine. But when I hit the save button I got an error: "This form post did not pass our security checks". Though the default url (siteurl/auth/edit_user/userID) works fine, For individual non-admin user I want to keep the url without userID at the end.
here is my edit_user() method:
//edit a user
function edit_user($id=NULL)
{
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id) && !($id==NULL )))
//if (!$this->ionauth->logged_in() || !$this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
if($id==NULL){
$user = $this->ion_auth->user()->row();
}else{
$user = $this->ion_auth->user($id)->row();
}
$groups=$this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
/**if (isset($user->phone) && !empty($user->phone))
{
$user->phone = explode('-', $user->phone);
} **/
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
if(!($this->input->post('email')==$user->email)){
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email|is_unique[users.email]');
}else{
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email');
}
/** $this->form_validation->set_rules('phone2', $this->lang->line('edit_user_validation_phone2_label'), 'required|xss_clean|min_length[3]|max_length[3]');
$this->form_validation->set_rules('phone3', $this->lang->line('edit_user_validation_phone3_label'), 'required|xss_clean|min_length[4]|max_length[4]');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean'); **/
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
//$this->form_validation->set_message('is_unique[users.email]','Email already exists or Invalid');
if (isset($_POST) && !empty($_POST))
{
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
{
show_error($this->lang->line('error_csrf'));
}
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
/** 'phone' => $this->input->post('phone1') . '-' . $this->input->post('phone2') . '-' . $this->input->post('phone3'), **/
);
//if($this->ion_auth->is_admin()){
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
}
}
//}
//update the password if it was posted
if ($this->input->post('password'))
{
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), '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', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
}
if ($this->form_validation->run() === TRUE)
{
$this->ion_auth->update($user->id, $data);
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth", 'refresh');
}
}
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//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')));
//pass the user to the view
$this->data['user'] = $user;
//if($this->ion_auth->is_admin()){
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
//}
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email', $user->email),
);
/** $this->data['phone1'] = array(
'name' => 'phone1',
'id' => 'phone1',
'type' => 'text',
'value' => $this->form_validation->set_value('phone1', $user->phone[0]),
);
$this->data['phone2'] = array(
'name' => 'phone2',
'id' => 'phone2',
'type' => 'text',
'value' => $this->form_validation->set_value('phone2', $user->phone[1]),
);
$this->data['phone3'] = array(
'name' => 'phone3',
'id' => 'phone3',
'type' => 'text',
'value' => $this->form_validation->set_value('phone3', $user->phone[2]),
); **/
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->load->view('header');
$this->_render_page('auth/edit_user', $this->data);
$this->load->view('footer');
}
and this is my view file (edit_user.php):
<h1><?php echo lang('edit_user_heading');?></h1>
<div id="body">
<p><?php echo lang('edit_user_subheading');?></p>
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open(uri_string());?>
<p>
<?php echo lang('edit_user_fname_label', 'first_name');?> <br />
<?php echo form_input($first_name);?>
</p>
<p>
<?php echo lang('edit_user_lname_label', 'last_name');?> <br />
<?php echo form_input($last_name);?>
</p>
<p>
<?php echo lang('edit_user_email_label', 'email');?> <br />
<?php echo form_input($email);?>
</p>
<!--
<p>
<?php echo lang('edit_user_phone_label', 'phone');?> <br />
<?php echo form_input($phone1);?>-<?php echo form_input($phone2);?>-<?php echo form_input($phone3);?>
</p>
-->
<p>
<?php echo lang('edit_user_password_label', 'password');?> <br />
<?php echo form_input($password);?>
</p>
<p>
<?php echo lang('edit_user_password_confirm_label', 'password_confirm');?><br />
<?php echo form_input($password_confirm);?>
</p>
<?php //if($this->ion_auth->is_admin()){ ?>
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php foreach ($groups as $group):?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php endforeach?>
<?php //} ?>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<p><?php echo form_submit('submit', lang('edit_user_submit_btn'));?></p>
<?php echo form_close();?>
The csrf check is failing.
Try taking out $id = NULL in the method declaration (you don't need it anyway if you're sending the id via POST). Or explicitly set $id = $this->input->post('id'); before doing the csrf check.
In my case I was using relative URLs for the images and css files used in the site. Using base_url() to all the URLs present in the site fixed the problem. No issue now.

2 date input validation php with condition

i want to validate 2 date input in codeigniter, with the conditions, if the end date is greater than the start date, will appear warning [javascript warning or something] or data can't be input
my form like this,
<h1><?php echo $title; ?></h1>
<form action="<?= base_url(); ?>index.php/admin/kalender/buat" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<p><label for='IDKategori'>Tingkatan Pimpinan :</label><br/>";
echo form_dropdown('IDKategori', $kategori) . "</p>";
echo "<label for='ptitle'>Kegiatan / Lokasi :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);
echo "<p><label for='long'>Uraian Kegiatan / Keterangan / Catatan :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Mulai :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Akhir :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2');
echo form_input($data) . "</p>";
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate in form "Waktu Akhir & Waktu Mulai" ?
Try this. It is by using CI validation library.
It uses callback type of validation.
Put this in if(isset($_POST['submit_button_name'])) {} section.
First, load validation array,
$validation = array(
array('field' => 'startDate', 'label' => 'StartDate', 'rules' => 'required|callback_compareDate'),
array('field' => 'endDate', 'label' => 'endDate', 'rules' => 'required|callback_compareDate'),
);
Then load CI validation library as,
$this->form_validation->set_rules($validation);
$this->form_validation->set_message('required', '%s is required.');
This is the called back function.
function compareDate() {
$startDate = strtotime($_POST['startDate']);
$endDate = strtotime($_POST['endDate']);
if ($endDate >= $startDate)
return True;
else {
$this->form_validation->set_message('compareDate', '%s should be greater than Contract Start Date.');
return False;
}
}
The "required" validation makes the fields mandatory to be filled with something.
The callback function, in this case, compares the dates, and further processes the form if start date is less than from date OR flags error otherwise.
Meanwhile, if you want in Jquery you can use this.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate > endDate){
alert("Start Date should be less than End Date");
return false;
}
This is working code
$params['toDate'] = $this->input->post('toDate', TRUE);
$params['fromDate'] = $this->input->post('fromDate', TRUE);$this->load->model('your_model');
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$startDate = strtotime($params['fromDate']);
$endDate = strtotime($params['toDate']);
if ($endDate >= $startDate):
$this->form_validation->set_rules('fromDate', 'From Date', 'required|trim');
$this->form_validation->set_rules('branchCode', 'Branch Code', 'required|trim');
else:
$json = array(
"success" => false,
"msg" => "Start date must be greater than end date"
);
echo json_encode($json);
die();
endif;

Categories