Ion Auth Flashdata Check Not Working - php

I am using Ben Edmunds Ion Auth Library.
I am having a problem with any function that uses the csrf_nonce methods - it is failing the check on post.
I have checked that the flashdata is getting set (I can see it in the form as a hidden input [edit_user for example]), but when you submit the form the flashdata check is failing.
I am using the database for the session if that makes any difference.
Code snippets;
Controller
function edit_user($id) {
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
redirect('auth', 'refresh');
} //!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()
$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);
} //isset($user->phone) && !empty($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');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
$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');
if (isset($_POST) && !empty($_POST)) {
// do we have a valid request?
if ($id != $this->input->post('id')) {
show_error($this->lang->line('error_csrf'));
} //$this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'email' => $this->input->post('email')
);
//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);
} //$groupData as $grp
} //isset($groupData) && !empty($groupData)
//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');
} //$this->input->post('password')
if ($this->form_validation->run() === TRUE) {
$check = $this->ion_auth->update($user->id, $data);
if (FALSE == $check) {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/edit-user/$id", 'refresh');
} else {
//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/users", 'refresh');
}
} //$this->form_validation->run() === TRUE
} //isset($_POST) && !empty($_POST)
//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;
$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['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company)
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'email',
'value' => $this->form_validation->set_value('email', $user->email)
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->_render_page('auth/admin/users/update', $this->data);
}
function _get_csrf_nonce() {
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array(
$key => $value
);
}
function _valid_csrf_nonce() {
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')) {
return TRUE;
} //$this->input->post($this->session->flashdata('csrfkey')) !== FALSE && $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
else {
return FALSE;
}
}
View;
<h1><?php echo lang('edit_user_heading');?></h1>
<p><?php echo lang('edit_user_subheading');?></p>
<!--<div id="infoMessage" class="info"><?php echo $message;?></div>-->
<?php
if (isset($message)) {
?>
<div id="infoMessage" class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Message</h4>
<?php echo $message;?>
</div>
<?php
}
?>
<?php echo form_open(uri_string(), 'class="form-horizontal"'); ?>
<div class="control-group <?php echo form_error_class('first_name') ?>">
<label class="control-label" for="first_name">
<?php echo lang('edit_user_fname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="first_name"
name="first_name"
placeholder="<?php echo lang('edit_user_fname_label'); ?>"
value="<?php echo set_value('first_name', $first_name['value']); ?>"
class="error"/>
<?php echo form_error('first_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('last_name') ?>">
<label class="control-label" for="last_name">
<?php echo lang('edit_user_lname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="last_name"
name="last_name"
placeholder="<?php echo lang('edit_user_lname_label'); ?>"
value="<?php echo set_value('last_name', $last_name['value']); ?>"
class="error"/>
<?php echo form_error('last_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('company') ?>">
<label class="control-label" for="company">
<?php echo lang('edit_user_company_label'); ?>
</label>
<div class="controls">
<input type="text"
id="company"
name="company"
placeholder="<?php echo lang('edit_user_company_label'); ?>"
value="<?php echo set_value('company', $company['value']); ?>"
class="error"/>
<?php echo form_error('company'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('email') ?>">
<label class="control-label" for="email">
<?php echo lang('edit_user_email_label'); ?>
</label>
<div class="controls">
<input type="text"
id="email"
name="email"
placeholder="<?php echo lang('edit_user_email_label'); ?>"
value="<?php echo set_value('email', $email['value']); ?>"
class="error"/>
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password') ?>">
<label class="control-label" for="password">
<?php echo lang('edit_user_password_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password"
name="password"
placeholder="<?php echo lang('edit_user_password_label'); ?>"
value="<?php echo set_value('password'); ?>"
class="error"/>
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password_confirm') ?>">
<label class="control-label" for="password_confirm">
<?php echo lang('edit_user_password_confirm_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password_confirm"
name="password_confirm"
placeholder="<?php echo lang('edit_user_password_confirm_label'); ?>"
value=""
class="error"/>
<?php echo form_error('password_confirm'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('groups') ?>">
<div class="controls <?php echo form_error_class('groups') ?>">
<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
}
?>
</div>
</div>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" value="<?php echo lang('edit_user_submit_btn'); ?>" />
</div>
</div>
<?php echo form_close();?>

First check
$this->session->set_flashdata('message',
$this->ion_auth->errors()
);
having set value

I have found the solution (or this fix works just for me).
I changed the session driver in the config to use native sessions from cookie.
Line 284 of config.php => $config['sess_driver'] = 'native';
Golden rule: never trust CI sessions!

Some notions about FLASHDATA
CSRF and Flashdata:
FLASHDATA will only be available for the NEXT server request, and are then automatically cleared!
e.g.:
AJAX calls function_1, which sends CSRF key/value back to function_1_success
function_1_success sets hidden input fields for CSFR key and value
and enables function_2, which compares POST variables with flashdata
this is how it works (with or without AJAX, that was just an example).
How it doesn't work: if you create a php function which does
$this->session->set_flashdata('item', 'value') and then try to read with echo $this->session->flashdata('item') you will get an empty string, only after a refresh of this function,your flashdata values show

Related

Codeigniter: Cannot upload files, Undefined Index : avatar

I cannot seem to upload files in codeigniter. I don't know if the issue lies with the if ($_FILES['avatar']['name'] == "").
My controller
private function upload_avatar($file)
{
$newName = $file->getRandomName();
$upload = $file->move(ROOTPATH . 'public/assets/avatar', $newName);
if ($upload) {
return $newName;
} else {
return false;
}
}
public function change_data()
{
helper(['form', 'url']);
$userModel = new UserModel();
if ($this->request->getMethod() == 'post') {
if ($_FILES['avatar']['name'] == "")
{
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]'
];
} else {
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]',
'avatar' => [
'uploaded[avatar]',
'mime_in[avatar,image/jpg,image/jpeg,image/png]',
'max_size[avatar,4096]'
]
];
}
if ($this->validate($rules)) {
if ($_FILES['avatar']['name'] == "") {
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
];
} else {
//get data user by session email
$user = $userModel->where('email', session()->get('email'))
->first();
if ($user) {
$deleteFile = unlink('./assets/avatar/' . $$user['avatar']);
if ($deleteFile) {
$file = $this->request->getFile('avatar');
$uploadFile = $this->upload_avatar($file);
}
}
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
'avatar' => $uploadFile,
];
}
$update = $userModel->update($user['id_user'], $params);
if ($update) {
session()->setFlashdata('success', 'Berhasil Update Data. Apabila Tampilan Data Belum Berubah, Silakan Lakukan Logout dan Login Kembali');
return redirect()->route('profile');
} else {
session()->setFlashdata('danger', 'Gagal Update Data');
return redirect()->route('edit')->withInput();
}
} else {
$data['validation'] = $this->validator;
}
}
$data['title'] = 'Edit Profile';
return view('admin/users/ubah_data', $data);
}
My view
<form action="<?= base_url('admin/user/change_data') ?>" method="POST">
<?= csrf_field(); ?>
<div class="form-group">
<label for="nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" value="<?= session()->nama ?>">
</div>
<div class="form-group">
<label for="nip">NIP</label>
<input type="text" class="form-control" id="nip" name="nip" value="<?= session()->nip ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="<?= session()->email ?>">
</div>
<div class="form-group">
<label for="tempat_lahir">Tempat Lahir</label>
<input type="text" class="form-control" id="tempat_lahir" name="tempat_lahir" value="<?= session()->tempat_lahir ?>">
</div>
<div class="form-group">
<label for="avatar">Foto <small>(Optional)</small></label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="avatar" name="avatar">
<label class="custom-file-label" for="avatar">Choose file</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info" />
</div>
</form>
After i push the upload button Undefined index: avatar message appeared.
Any help will be greatly appreciated. I cannot seem to figure out why ($_FILES['avatar']['name'] == "") has problem
I think you miss to include enctype="multipart/form-data" in form tag
<form action="url-action" method="POST" enctype="multipart/form-data">
your form
</form>

Failed Upload Files Codeigniter

I'm try to make crud with upload file but somehow it's keep return FALSE but i don't know what's wwrong with my code if i var_dump($data) before condition upload it's show the name of my image but if i var_dump($uploads) it's keep show false
This is my controller
public function saveReimburse()
{
validate_submitted_data(array(
'nama' => 'required',
'category_reimburse_id' => 'required',
'amount' => 'required|numeric',
'date_reimburse' => 'required',
));
// data
$data = [
'nama' => $this->input->post('nama'),
'category_reimburse_id' => $this->input->post('category_reimburse_id'),
'amount' => $this->input->post('amount'),
'date_reimburse' => $this->input->post('date_reimburse'),
'photo' => $_FILES['photo'],
];
// condition
$date = date('Y-m-d');
$date = strtotime($date);
$date = strtotime('-7 day', $date);
if ($data['date_reimburse'] < date('Y-m-d', $date)) {
echo json_encode(array('succes' => FALSE, 'message' => 'Max Reimburse was 1 week ago'));
} else {
if ($data['photo'] = "") {
} else {
$config = [
'upload_path' => './assets/reimburse',
'allowed_types' => 'jpg|png|gif',
'overwrite' => TRUE
];
$this->load->library('upload', $config);
$upload = $this->upload->do_upload('photo');
var_dump($upload);exit;
if (!$upload) {
json_encode(array('success' => FALSE, 'message' => 'Failed Upload'));
redirect('Reimburse/index', 'refresh');
} else {
$this->upload->data('file_name');
$save = $this->reimburseModel->saveReimburse('reimburse', $data);
var_dump($data);exit;
if (!$save) {
echo json_encode(array('success' => FALSE, 'message' => 'Failed to reccord'));
} else {
redirect('Reimburse/index', 'refresh');
echo json_encode(array('success' => TRUE, 'message' => 'Reimburse Success'));
}
}
}
}
}
and this my model
function saveReimburse($table,$data)
{
$this->load->database('default', TRUE);
if(!$this->db->insert($table,$data))
return FALSE;
$data["id"] = $this->db->insert_id();
return (object) $data;
}
This is my input code
<?php echo form_open_multipart(get_uri("Reimburses/saveReimburse"), array("id" => "formReimburse", "class" => "general-form", "role" => "form")); ?>
<div id="expense-dropzone" class="post-dropzone">
<div class="modal-body clearfix">
<!-- <form action =" " method='POST'> -->
<div class="form-group">
<label for="Nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" placeholder="Nama">
</div>
<div class="form-group">
<label for="category_reimburse_id">Category</label>
<select class="form-control form-control-lg" name="category_reimburse_id">
<option value ="">-</option>
<?php
foreach($category as $ct){?>
<option value ="<?php echo $ct->id ?>"><?php echo $ct->category ?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label for="amount">Amount</label>
<input type="text" class="form-control" id="amount" name="amount" placeholder="Amount">
</div>
<div class="form-group">
<label for="date_reimburse">Date</label>
<input type="date" class="form-control" id="date_reimburse" name="date_reimburse" value='<?php echo date('Y-m-d') ?>'>
</div>
<div class="form-group">
<div class="form-group">
<label for="photo">Input Photo</label>
<input type="file" class="form-control-file" id="photo" name ="photo">
</div>
</div>
<div class="float-right">
<button type="cancel" class="btn btn-warning ">Cancel</button>
<button type="submit" class="btn btn-primary ">Submit</button>
</div>
<!-- </form> -->
</div>
</div>
<?php echo form_close() ?>
Check the error using the error function
print_r($this->upload->display_errors());
Try adding bellow upload path
'upload_path' => '../assets/reimburse';
Put one / after reimburse like "./assets/reimburse/" can solve problem may be and assets folder in root directory

How can i add two image from two different inputs on single page in codeigniter

I am trying to upload two images in database at once submit attempt from single form that have two different file input fields.
I tried but its not working when i try to show result using print_r it gives a single file name for both input fields. How can i do it perfectly in codeigniter. please help for your reference i am uploading my code. you if any error please let me know.
HTML Form Code
<form id="form_edit" method="post" action="<?php echo base_url(" admin/aboutus/update/".$aboutus->id); ?>" enctype="multipart/form-data" accept-charset="utf-8">
<div class="form-group row">
<div class="col-md-4 col-xs-4">
<input type="text" name="imgtitle" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->imgtitle); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'imgdetail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->imgdetail)]); ?>
<input type="file" name="img" title="About Us Image" class="form-control input-sm">
</div>
<div class="col-md-4 col-xs-4">
<input type="text" title="About Us Title" class="form-control input-sm" name="title" value="<?php echo set_value('title', $aboutus->title); ?>" placeholder="Type left side title of about us of maximum 15 characters" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'detail','title'=>"About Us Detail",'class'=>'form-control mptop input-sm mptop','required'=>'required','value'=> set_value('detail', $aboutus->detail)]); ?>
</div>
<div class="col-md-4 col-xs-4">
<input type="text" name="img_2title" title="About Us Image Title" class="form-control input-sm" value="<?php echo set_value('imgtitle', $aboutus->img_2title); ?>" placeholder="Image Title" required="required">
<?php echo form_textarea(['rows'=>'15', 'name'=>'img_2detail','title'=>'About Us Image Description','class'=>'form-control mptop input-sm','required'=>'required','value'=> set_value('detail', $aboutus->img_2detail)]); ?>
<input type="file" name="img_2" title="About Us Image" class="form-control input-sm">
<!-- id="detail" -->
</div>
</div>
<div class="form-group row">
<div class="col-md-12 col-xs-12 mptop rmzero rpZero">
<div class="btn-group pull-right text-right">
<i class="fa fa-arrow-left"></i> Back
<!-- <i class="fa fa-search"></i> Preview -->
<button type="submit" class="btn btn-success btn-sm" name="submit" id="save"><i class="fa fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
My Codeigniter Control Code
public function update($id)
{
$res = array();
//form field validation rules
$this->form_validation->set_rules('title', 'Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('detail', 'Detail', 'required|max_length[2000]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgtitle', 'Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('imgdetail', 'Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2title', 'Second Image Title', 'required|max_length[15]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$this->form_validation->set_rules('img_2detail', 'Second Image Description', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors('')));
exit;
}
$config['upload_path'] = 'fassets/images/aboutus';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//$config['file_name'] = $_FILES['img']['name'];
$config['overwrite'] = TRUE;
//Load upload library and initialize configuration
$this->load->library('upload', $config);
// echo $image_path; exit;
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail')
);
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
else
{
$userData = array(
'title' => $this->input->post('title'),
'detail' => $this->input->post('detail'),
'imgtitle' => $this->input->post('imgtitle'),
'imgdetail' => $this->input->post('imgdetail'),
'img_2title' => $this->input->post('img_2title'),
'img_2detail' => $this->input->post('img_2detail'),
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
);
echo "<pre>";
print_r($userData);
exit;
//Pass user data to model
$insertUserData = $this->AboutusModel->update($userData, $id);
}
//Storing insertion status message.
if($insertUserData){
$res = array(
'mes' => 'text-success',
'msg' => "Record has been saved successfully.",
);
echo json_encode($res);
} else {
$res = array(
'mes' => 'text-danger',
'msg' => "Oops! Something went wrong.",
);
echo json_encode($res);
}
}
With $this->upload->data('file_name'), you are getting only the last uploaded file name. You're missing the first one. To solve this simple issue, store both filenames in variables to use after both files have successfully been uploaded.
Before:
$this->load->library('upload', $config);
Add:
$img1 = $_FILES['img']['name'];
$img2 = $_FILES['img_2']['name'];
Replace:
'img' => $this->upload->data('file_name'),
'img_2' => $this->upload->data('file_name')
With:
'img' => $img1,
'img_2' => $img2
Another Issue:
In your current code, if your first upload succeeds the second will fail. To prevent that.
Replace:
if((!$this->upload->do_upload('img')) && (!$this->upload->do_upload('img_2')))
With:
$upload1_ok = $this->upload->do_upload('img');
$upload2_ok = $this->upload->do_upload('img_2');
if($upload1_ok == false && $upload2_ok == false)

How to avoid duplication when submitting data to json file via php?

I have a code that submits data into a cake json 'database', but when I submit using PHP. When I reload the page, the file repeats the code of the last object in the JSON file when I get it. How do I avoid this?
This is my PHP
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["type"]))
{
$error = "<label class='text-danger'>Enter Type</label>";
}
else if(empty($_POST["diff"]))
{
$error = "<label class='text-danger'>Enter Difficulty</label>";
}
else
{
if(file_exists('../../databases/cakes.json'))
{
$current_data = file_get_contents('../../databases/cakes.json');
$array_data = json_decode($current_data, true);
$extra = array(
'person' => array(
'name' => $_POST['name'],
'difficulty' => $_POST["diff"],
'type' => $_POST["type"],
'isNew' => 'true',
'isVeg' => 'false',
)
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('../../databases/cakes.json', $final_data))
{
//.-.
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
<body>
<div id="layout"></div>
<div id="content">
<div id="add">
<div class="form-title"><h1>Add Cake</h1></div>
<form method="post">
<?php
if(isset($error))
{
echo $error;
}
?>
<br />
<div class="input-field">
<label for="name">Cake Name</label>
<input type="text" name="name"/>
</div>
<br />
<div class="input-field">
<label for="diff">Difficulty</label>
<div class="select">
<select name="diff" id="slct">
<option>Choose an option</option>
<option value="male">EZ</option>
<option value="female">Meh</option>
<option value="matthew">Mildy Hard</option>
</select>
</div>
</div>
<br />
<div class="input-field">
<label for="type">Type</label>
<input type="text" name="type"/><br />
Need Suggestions?<br>
</div>
<input class="addCake" type="submit" name="submit" value="Add Cake!"/><br />
See some other cakes
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
Submission Works.
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
But when I reload the page I see two of this things...
Result:
[[{"cake":{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"},{"name":"tes1","diff":"EZ","type":"Deli","isNew":"true","isVeg":"false"}}]]
Use ($_SERVER['REQUEST_METHOD'] == 'POST') instead of ($_POST["submit"])
$array_data = array_merge($array_data, $extra); instead of $array_data[] = $extra;

codeigniter pass data from view to controller

I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>

Categories