$_FILES['imagem'] is undefined in Firefox - codeigniter

My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.

If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}

Related

LARAVEL Get file Content and split to save in another table

Hi everyone I need your help on how to split value from textarea and insert in a users table using laravel, I was able to get file content = "name | username | password", I need to split each value so I ca save it to a users table the file itself is save in a different table, should I put it in a different method or just specify my target table in the same as the file will be saved? Your help will be much appreciated.
UploadController:
public function store(Request $request){
$validator = Validator::make(
$request->all(),
['filename' => 'required|mimes:txt,jpeg,png,jpg,bmp|max:2048']
);
if ($validator->fails()) {
return back()->withErrors($validator->errors());
}
// if validation success
if ($file = $request->file('filename')) {
$filename = 'uploaded-here.' . $file->getClientOriginalExtension();
//stored in laravel local storage
$target_path = $file->storeAs('uploaded-here/', $filename);
if ($file->move($target_path, $filename)) {
// save file name in the database
$file = File::create(['filename' => $filename]);
return back()->with("success", "File uploaded successfully");
}
}
}
html code:
<div class="form-group" {{ $errors->has('filename') ? 'has-error' : '' }}>
<label for="filename"></label>
<input type="file" name="filename" id="filename" class="form-control">
<span class="text-danger"> {{ $errors->first('filename') }}</span>
<textarea id="editor" name="editor></textarea>
</div>
<button type="submit" class="btn btn-success btn-md"> Upload </button>
js
window.onload = function() {
var doc = document.getElementById('filename');
if (doc) {
doc.addEventListener('change', getFile);
}
}
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('editor'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
There is an error. Quotation closed sign is missing in name attribute of textarea.
<textarea id="editor" name="editor"></textarea>
You can split using JavaScipt's split() method. Like follwoing:
Say, you have the textarea value as your given format: name | email | password
as you have given example: example errol | errol.boneo13#gmail.com | password123.
Let's say, you have get the textarea value,
var textValue = document.getElementById('editor').value;
textValue = textValue .split(" | ");
var name = textValue [0];
var email = textValue [1];
var password = textValue [2];
Hope it helps....
EDIT::
As you wanted to do in laravel, you can do like following:
$textValue = $request->editor;
$textValue = explode(" | ", $textValue );
$name = $textValue [0];
$email = $textValue [1];
$password = $textValue [2];

getMimeType() before moving file in Laravel

This a part of my app I'm using to put a section that admin can choose the category of the file from...
File Model
namespace App\Models;
use App\Traits\Categorizeable;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use Categorizeable;
protected $primaryKey = 'file_id';
protected $guarded = ['file_id'];
public function packages()
{
return $this->belongsToMany(Package::class, 'package_file');
}
}
Anyway I used a trait for it...
after that it is my view:
<div class="form-group">
<label for="categorize"> categories :</label>
<select name="categorize[]" id="categorize" class="select2 form-control" multiple>
#foreach($categories as $cat)
<option value="{{$cat->category_id}}"
{{isset($file_categories) && in_array($cat->category_id,$file_categories) ? 'selected' :'' }}>
{{$cat->category_name}}</option>
#endforeach
</select>
</div>
at last this is my FilesController:
public function store(Request $request)
{
// $this->validate();....
//after validation
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $request->file('fileItem')->getMimeType(),
'file_size' => $request->file('fileItem')->getClientSize(),
]);
if ($new_file_data) {
if ($request->has('categorize')) {
$new_file_data->categories()->sync($request->input('categorize'));
}
return redirect()->route('admin.files.list')->with('success', 'message');
}
}
}
Now what my problem is that as you see file() saves a .tmp file first and I need to use getMimeType() before I move it, how to modify my code?
What is the best way to do that?
App is giving me an Error
Save the mime type as a variable before you move the file and use it in the create function
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$mime_type = $request->file('fileItem')->getMimeType();
$file_size = $request->file('fileItem')->getClientSize();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $mime_type,
'file_size' => $file_size,
]);

How to Set or retrieve old Path image when we not update the image in the form multiple images in Codeigniter 2.2.6

I have edit form in codeigniter in that form i have 15 more image file while i update the image it updating in database but even am not update the images in the form it goes and save as null or empty path .But i need solution for that when am not update all 15 files should retrive the same old image path which it is stored in database.Please Could you guys give better solution for this.
My Edit Form
controller:
if($this->input->post('submit'))
{
if($_FILES['file']['name']!='')
{
$filename = $_FILES['file']['name'];
$file_name1 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name1;
$file ="uploads/images/".$file_name1;
}
if($_FILES['file1']['name']!='')
{
$filename = $_FILES['file1']['name'];
$file_name2 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name2;
$file ="uploads/images/".$file_name2;
}
$query = $this->scener_model->popular_upload($file_name1,$file_name2)
}
If your is empty then pass hidden input value or else pass newly uploaded value like this..
if(!empty($_FILES()){
//your uploaded value here
} else {
//hidden attribute value
}
if($this->input->post('submit1')){
$titlemain = $this->input->post('title_main');
$price = $this->input->post('price');
$package = $this->input->post('package');
$titleinner = $this->input->post('title_inner');
$city_package = $this->input->post('city_packge');
if(!empty($count =count($_FILES['file1']['name']))){;
for($i=0; $i<$count;$i++){
$filename1=$_FILES['file1']['name'][$i];
//print_r($filename);exit;
$filetmp=$_FILES['file1']['tmp_name'][$i];
$filetype=$_FILES['file1']['type'][$i];
$images = $_FILES['file1']['name'];
$filepath="uploads/images/".$filename1;
move_uploaded_file($filetmp,$filepath);
}
$filename1 = implode(',',$images);
}
else{
$filename1=$this->input->get('iti_image2') ;
//print_r( $data['newz1']);exit;
}
my view page:
<div class="col-sm-8">
<input type="button" id="get_file" value="Grab file">
<?php
$imss= $result->iti_image2;
?>
<input type="file" id="my_file" name="file3[]" value="<?php echo $imss ?>" multiple/>
<div id="customfileupload">Select a file</div>
<input type="hidden" class="btn btn info" id="image" name="iti_image2" accept="image" value="<?php echo $result->iti_image2; ?>" multiple/ >
</div>
<script>
document.getElementById('get_file').onclick = function() {
document.getElementById('my_file').click();
};
$('input[type=file]').change(function (e) {
$('#customfileupload').html($(this).val());
});
</script>
</div>
my Model:
function itinerary_updte($filename4,$filename5){
$update_itinerarys = array(
'iti_image2' =>$filename4,
'iti_image3' =>$filename5
);
$this->db->where('id', $id);
$result = $this->db->update('sg_itinerary', $update_itinerarys);
return $result;
}
Finally guys i found a solution for image updating follwing some tutorials see the link
"http://www.2my4edge.com/2016/04/multiple-image-upload-with-view-edit.html"
thanks buddies who are give the logic and commenting on my post and thanks alot #ankit singh #Lll

Polling Chat message content to screen using ajax JSON

Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]

CodeIgniter - I can't update row in my table

I can't find the correct way update one row in my table.
My view:
...
<?php echo form_open('ImenikController/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Ime i prezime*:
<input type='text' name='ime_prezime' value=""> <br><br>
Ulica i broj: <input type='text' name='ulica' value=""> <br><br>
Mesto: <input type='text' name='mesto' value=""> <br><br>
Telefon*: <input type='text' name='telefon' value=""> <br><br>
<u>Napomena: Polja sa zvezdicom su obavezna.</u> <br /> <br />
<input background:url('images/login-btn.png') no-repeat; border: none;
width='103' height='42' style='margin-left:90px;' type='submit' value='Izmeni'>
<?php echo form_close(); ?>
...
My Controller:
function verify_editing_phonebook()
{
if ($this->session->userdata('logged_in'))
{
if ($this->session->userdata('admin') == 1)
{
$this->form_validation->set_rules('ime_prezime', 'Ime i prezime', 'trim|required|xss_clean');
$this->form_validation->set_rules('telefon', 'Telefon', 'trim|required|xss_clean');
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
}
else {
$temp = $this->session->userdata('logged_in');
$obj['id'] = $temp['id'];
$data['records'] = $this->LoginModel->get_Username($obj);
$this->load->view('ErrorEditing', $data);
}
}
else {
$this->load->view('restricted_admin');
}
}
else {
$this->load->view('restricted');
}
}
My Model:
function edit_phonebook($id)
{
$data = array ('ime_prezime' => $this->input->post('ime_prezime'),
'ulica' => $this->input->post('ulica'),
'mesto' => $this->input->post('mesto'),
'telefon' => $this->input->post('telefon'));
$this->db->where('id', $id);
$this->db->update('pregled', $data);
}
That solution doesn't work.
I get the url: localhost/imenik114/ImenikController/verify_editing_phonebook
It is a blank (white) page. And not editing row in table.
Basic Debugging Strategies
(1) Have you created all the view files?
(2) Have you tested edit_phonebook($id) independently?
(3) What does redirect(site_url().'ImenikController/', 'refresh'); display?
Did you define the index function for ImenikController?
(4) What URL did you use when you say 'That solution doesn't work.' ?
(5) If your URL is: "localhost/imenik114/ImenikController/verify_editing_phonebook"
you did not type in id in your 3rd segment
(6) If you are not logged in, do you see the correct restricted view?
(7) If you are logged in and NOT admin, do you see the correct restricted_admin view?
Potential Bug
Looking at this part of your code:
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
// You need to handle the case of $id not set
else
{
// load a view with error page saying $id is missing...
}
}
if your form validates, and you don't pass in segment(3), your controller will not load a view, therefore, you will get a blank page.
You need to check the case of $id not present, see code.
Code Fix
One more detail: the statement $id = $this->uri->segment(3); will set $id either to the id number or FALSE, therefore, you don't need isset($id) in your if statement. I would write $id = $this->uri->segment(3,0); to set the default to 0 instead of FALSE to keep the logic a bit clearer.
Thanks for answer but I solved my problem somehow.
I made a link in my view:
Edit
And in view for editing:
<?php echo form_open('Controller/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Function verify_editing_phonebook passed trough validation and loading view.
Thanks once again and sorry for my English...

Resources