I am using CodeIgniter framework for PHP.And I couldn't upload/update a photo.
Here is the edit-profile1.php View:
<form action="<?php echo base_url(); ?>users/update/" method="post" enctype="multipart/form-data" data-toggle="validator">
<div class="container">
<div class="padd col-xs-12 col-md-3">
<label class="label">My IC/Matric Card</label></br>
<input name="image" placeholder="Upload" class="upload friendly" type="file" accept="image/*" capture="environment" required>
</div>
<div class="col-xs-12 col-md-9 padd" style="overflow:auto;">
<div class="picture"><img id="blah" style="width: 100%; height: 100%"
<?php
if($userdata[0]['image'] == "")
{
echo "src='https://style.anu.edu.au/_anu/4/images/placeholders/person.png'";
}else{
echo "src='" . str_replace('/index.php/','/',base_url())."media/images/users/".$userdata[0]['image']."'";
}
?> >
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
<button type="submit" style='width: 100%; margin-top:20px; margin-bottom: 20px !important; background-color: #59d389; color: white;' class="btn btn-responsive btn-md center-block">Save Changes</button>
<input type="hidden" value="<?php echo $userdata[0]['id']; ?>" name="id" />
<input type="hidden" value="<?php echo $userdata[0]['account_status']; ?>" name="id" />
<input type="hidden" value="<?php echo $userdata[0]['image']; ?>" name="oldimage"/>
</div>
</div>
</div>
</form>
Here is the Users.php Controller:
public function profile()
{
$data['userdata'] = $this->usermodel->get_user($this->session->userdata('id'));
$this->load->view('edit-profile1',$data);
}
public function update()
{
$user = new Users_model();
// $user->phone1 = $this->input->post('phone1');
$user->account_status = 1;
//session data
$user->id = $this->session->userdata('id');
$user->password = $this->session->userdata('password');
$user->username = $this->session->userdata('username');
$user->email = $this->session->userdata('email');
$user->user_role = $this->session->userdata('user_role');
//id to be set
$id = $user->id;
if($_FILES['image'])
{
/* IMAGE UPLOADING START */
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];
$image_tmp=$_FILES['image']['tmp_name'];
$d=date('YmdHis');
//$image_test_name = str_replace(" ", "_", $user->firstname.$user->lastname);
$image_type = str_replace("image/", ".", $image_type);
$image_name=$user->id . $image_type;
$imgurl= str_replace("/index.php/","/",base_url())."media/images/users/".$image_name;
if($image_type==".jpeg" || $image_type==".png" || $image_type==".gif" )
{
$this->usermodel->upload_user_image($image_name);
$this->usermodel->update_image($user->id, $image_name);
$user->image = $image_name;
}
else
{
$user->image = $this->input->post('oldimage');
}
/* IMAGE UPLOADING END */
}else{
$user->image = $this->input->post('oldimage');
}
$res = $this->db->update('users', $user, array('id' => $id));
$URL = base_url() . "users/profile/";
redirect($URL, "refresh");
}
}
And here is the Users_model.php Model:
public function upload_user_image($image_name) {
$config['upload_path'] = 'media/images/users';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = TRUE;
$config['file_name'] = $image_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image')) {
$this->upload->display_errors('<span>', '</span>');
$data['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$data['success'] = "Your file is uploaded";
}
}
public function update_image($id,$image_name){
$sql = "update users set image = '$image_name' where id = $id ";
$this->db->query($sql);
}
When the page redirect, the image is uploaded. The problem is, when refreshing manually, the placeholder image appear again and it means the photo wasn't updated to the database.
Here is the link to the website: https://www.yiyalo.com
You can log in using these credentials
id: qy_leong13#hotmail.com
pass: 123456
GO to My account > My profile to try it out
You need to upload file in controller itself. If you are using file upload library then don't need to do it manually with $_FILES variable.
public function update()
{
$user = new Users_model();
// $user->phone1 = $this->input->post('phone1');
$user->account_status = 1;
//session data
$user->id = $this->session->userdata('id');
$user->password = $this->session->userdata('password');
$user->username = $this->session->userdata('username');
$user->email = $this->session->userdata('email');
$user->user_role = $this->session->userdata('user_role');
//id to be set
$id = $user->id;
$config['upload_path'] = 'media/images/users';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = TRUE;
//$config['file_name'] = $image_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image')) {
$this->upload->display_errors('<span>', '</span>');
$data['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$data['success'] = "Your file is uploaded";
}
$res = $this->db->update('users', $user, array('id' => $id));
$URL = base_url() . "users/profile/";
redirect($URL, "refresh");
}
Related
so i try to make some upload form which will upload some image. but when the image has chosen then the button submit has clicked the result say "You did not select a file to upload."
im using php, with codeigniter framework
The view
<form class="text-left" enctype="multipart/form-data" method="post" action="<?= base_url('aduan/add'); ?>">
<div class="form-group">
<label>Upload Foto Bukti Aduan</label>
<div class="form-group">
<label>Bukti Aduan 1</label>
<input class="form-control-file" type="file" id="bukti1" name="bukti_aduan1" />
<?= form_error('bukti_aduan1', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
<div class="form-group">
<label>Bukti Aduan Pelapor di Lokasi</label>
<input class="form-control-file" type="file" id="bukti2" name="bukti_aduan2" />
<?= form_error('bukti_aduan2', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
</div>
which the view will run the controller "aduan" for input function
Controller file:
$aduan = $this->aduan_model;
$validation = $this->form_validation;
$validation->set_rules($aduan->rules());
if ($validation->run()) {
$aduan->tambah();
$this->session->set_flashdata('success', 'Berhasil disimpan');
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/aduansukses');
$this->load->view('home/home_footer');
} else {
$data['aduan'] = $this->aduan_model->getAll();
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/buataduan');
$this->load->view('home/home_footer');
}
then the controller will load a model which is "aduan_model"
Model file :
public function tambah()
{
$post = $this->input->post();
$this->nik_pelapor = $post["nik_pelapor"];
$this->nama_pelapor = $post["nama_pelapor"];
$this->email_pelapor = $post["email_pelapor"];
$this->telp_pelapor = $post["telp_pelapor"];
$this->alamat_pelapor = $post["alamat_pelapor"];
$this->aduan = $post["aduan"];
$this->bukti_aduan1 = $this->_uploadImage();
$this->bukti_aduan2 = $this->_uploadImage2();
$this->status_aduan = 'Dalam proses';
$this->tgl_aduan = time();
$this->db->insert($this->_table, $this);
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan1')) {
return $this->upload->data();
}
return "default.jpg";
}
private function _uploadImage2()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan2')) {
return $this->upload->data();
}
return "default.jpg";
}
i expect the output of image can be stored in file upload and inserted in database but it doesnt select any file
please help :)
try my code
replace if condition in controller to upload
if(
(!$this->upload->do_upload('bukti_aduan2')) &&
(! $this->upload->do_upload('bukti_aduan1'))
)
{
echo "failed";
}
else
{
echo "success";
}
I want to insert data with multiple file, but the file is null if i insert to database. this is my code
FROM ACTION CODE
<form action="<?php echo base_url();?>SystemCore/tambahKendaraan" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Foto Foto Kendaraan</label>
<input type="file" class="form-control" multiple="" required="" name="addKendaraanDinasFoto[]">
<small>*Dapat Mencantumkan Foto Lebih Dari 1</small>
</div>
<button type="submit" class="btn btn-success">Simpan</button>
</form>
This i my Controller to upload data
public function tambahKendaraan()
{
$simpanData = array(
"id_jenis" => $this->input->post("addKendaraanDinasJenis"),
"plat_kendaraan" => $this->input->post("addKendaraanDinasPlat"),
"dinas_pengelola" => $this->input->post("addKendaraanDinasPengelola"),
"pemegang_kendaraan" => $this->input->post("addKendaraanDinasPemegang"),
"no_stnk" => $this->input->post("addKendaraanDinasSTNK"),
"no_rangka" => $this->input->post("addKendaraanDinasRangka"),
"masa_pajak" => $this->input->post("addKendaraanDinasPajak"),
"merk_kendaraan" => $this->input->post("addKendaraanDinasMerk"),
"warna_kendaraan" => $this->input->post("addKendaraanDinasWarna"),
"status_kendaraan" => $this->input->post("addKendaraanDinasStatus"),
);
if ($this->db->insert("tbl_mobil", $simpanData)) {
$insert_id = $this->db->insert_id();
date_default_timezone_get("Asia/Jakarta");
$this->load->library('upload');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['addKendaraanDinasFoto']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['addKendaraanDinasFoto']['name']= $files['addKendaraanDinasFoto']['name'][$i];
$_FILES['addKendaraanDinasFoto']['type']= $files['addKendaraanDinasFoto']['type'][$i];
$_FILES['addKendaraanDinasFoto']['tmp_name']= $files['addKendaraanDinasFoto']['tmp_name'][$i];
$_FILES['addKendaraanDinasFoto']['error']= $files['addKendaraanDinasFoto']['error'][$i];
$_FILES['addKendaraanDinasFoto']['size']= $files['addKendaraanDinasFoto']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$dataInfo[] = $this->upload->data();
$this->db->insert("tbl_fotomobil", $data);
}
foreach ($dataInfo as $infos) {
$data = array(
'id_mobil' => $insert_id,
'tgl_foto' => date('Y-m-d H:i:s'),
'foto_mobil' => $infos['file_name'],
);
}
$this->session->set_flashdata('notif', '<script>swal ( "Success" , "Data Kendaraan Berhasil Ditambahkan !" , "success" );</script>');
}else{
$this->session->set_flashdata('notif', '<script>swal ( "Error" , "Data Error !" , "error" );</script>');
}
redirect('kendaraan');
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = './upload/kendaraan/';
$config['allowed_types'] = 'jpg|png|jpeg|svg';
$config['max_size'] = 10097152;
$config['overwrite'] = FALSE;
return $config;
}
Result:
array(3) {
["id_mobil"]=>
int(0)
["tgl_foto"]=>
string(19) "2019-07-09 09:55:58"
["foto_mobil"]=>
string(0) ""
}
array(3) {
["id_mobil"]=>
int(0)
["tgl_foto"]=>
string(19) "2019-07-09 09:55:58"
["foto_mobil"]=>
string(0) ""
}
Controller :::
public function addmember()
{
if (empty($_FILES['user_image']['name']))
{
$this->form_validation->set_rules('user_image', 'User Image', 'required');
}
if (empty($_FILES['user_gallery']['name']))
{
$this->form_validation->set_rules('user_gallery[]', 'User Gallery', 'required');
}
if($this->form_validation->run() == FALSE)
{
$this->load->view('common_page/header');
$this->load->view('common_page/sidebar');
$this->load->view('form');
$this->load->view('common_page/footer');
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if($this->upload->do_upload('user_image') && !empty($_FILES['user_gallery']['name']))
{
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$dataInfo = [];
$files = $_FILES;
$cpt = count($_FILES['user_gallery']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['user_gallery']['name'] = $files['user_gallery']['name'][$i];
$_FILES['user_gallery']['type'] = $files['user_gallery']['type'][$i];
$_FILES['user_gallery']['tmp_name'] = $files['user_gallery']['tmp_name'][$i];
$_FILES['user_gallery']['error'] = $files['user_gallery']['error'][$i];
$_FILES['user_gallery']['size'] = $files['user_gallery']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('user_gallery');
$dataInfo[] = $this->upload->data();
}
$all_imgs = '';
if ( count($dataInfo) > 0) {
foreach ($dataInfo as $info) {
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$data = [
'user_image' => $uploadedFile,
'user_gallery' => $all_imgs
];
$this->Admin_model->insertData($data,'member');
$this->session->set_flashdata('success', 'Member Register Successfully !!!');
redirect('all/form');
}
else
{
}
}
}
VIEW :::
<form role="form" id="member_form" action="<?php echo
base_url('all/addmember');?>" method="post" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">User Image</label>
<input type="file" id="file" name="user_image">
<?php echo form_error('user_image', '<div class="error">', '</div>'); ?>
</div>
<div class="form-group">
<label for="exampleInputFile">User Gallery Image</label>
<input type="file" id="gallery" name="user_gallery[]" multiple="">
<?php echo form_error('user_gallery', '<div class="error">', '</div>'); ?>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
I am stuck here.. I was trying to upload image and video, image upload working fine but while uploading video getting the error as "The filetype you are attempting to upload is not allowed.". I have tried all the answers but unfortunately couldn't workout. Can someone plz help me. What Am I doing wrong? Thanks.
My View 'home':
<div style="margin-right: 17px;">
<label>Name:</label>
<input type="text" name="name" value="<?php echo set_value('name');?>">
<?php echo form_error('name','<div class="error">','</div>'); ?>
</div>
<div style="padding:20px 20px">
<label>Upload Image</label>
<input type="file" name="photo">
</div>
<div style="padding:5px 5px">
<label>Upload Video</label>
<input type="file" name="video">
</div>
<div style="padding:10px 10px">
<input type="submit" name="sumit" value="Submit">
</div>
</form>
My Controller:
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if(! $this->form_validation->run()){
$data['useradded'] = "";
}
else{
if(isset($_FILES['photo']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/";
$config['allowed_types'] = "jpg|png|gif";
$config['max_size'] = '2048';
$config['max_width'] = '0';
$config['max_height'] = '0';
$new_name = "photo_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('photo')){
$data['error'] = array('error' => $this->upload->display_errors());
$photo_name = "";
}else{
$photo_name = $new_name;
}
}
if(isset($_FILES['video']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/videos/";
$config['allowed_types'] = "avi|flv|wmv|mpg|mpeg|mp3|mp4";
//$config['allowed_types'] = "video/x-msvideo|image/jpeg|video/mpeg|video/x-ms-wmv";
$config['max_size'] = '0';
$new_name = "video_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('video')){
$data['error'] = array('error' => $this->upload->display_errors());
$video_name = "";
}else{
$video_name = $new_name;
}
}
$this->complaints_model->add_complaint($photo_name,$video_name);
$data['useradded'] = "New complaint added Successfully";
}
$this->load->view('home', $data);
I'm new to codeigniter, and I'm trying to make a form that updates a profile. It has worked before but now it doesn't anymore.
I changed something in the view and it stopped working. I changed it back to where it was but it doesn't work anymore. I spend half a day trying to make it work again but I failed.
Maybe I don't see what you guys can see. At least I hope so.
this is my view:
<?php echo form_open_multipart('Gids/do_upload');?>
<img width="200px" src="<?php echo base_url()."uploads/".$profile[0]['image']; ?>" alt=""/>
<label for="">Uploade new picture:</label><input type="file" name="userfile" size="20" value="128.jpg" >
<input style="display: none" id="image" name="image" type="text" value="<?php echo "profile_picture".$_SESSION['id'].".jpg"; ?>"/>
<label for="naam">Naam:</label><input id="naam" name="naam" type="text" value="<?php echo $profile[0]['naam']; ?>"/>
<label for="voornaam">Voornaam:</label><input id="voornaam" name="voornaam" type="text" value="<?php echo $profile[0]['voornaam']; ?>"/>
<label for="email">Gebruikersnaam:</label><input id="gebruikersnaam" name="gebruikersnaam" type="text" value="<?php echo $profile[0]['gebruikersnaam']; ?>"/>
<label for="email">Email:</label><input id="email" name="email" type="text" value="<?php echo $profile[0]['email']; ?>"/>
<label for="opleiding">Opleiding:</label><input id="opleiding" name="opleiding" type="text" value="<?php echo $profile[0]['opleiding']; ?>"/>
<label for="school">School:</label><input id="school" name="school" type="text" value="<?php echo $profile[0]['school']; ?>"/>
<label for="wachtwoord">Wachtwoord:</label><input id="wachtwoord" name="wachtwoord" type="text" />
<label for="typeAgain">Type Opnieuw:</label><input id="typeAgain" type="text" />
<label for="over">Over mezelf:</label><textarea name="over" id="over" cols="30" rows="10"><?php echo $profile[0]['over']?></textarea>
<input type='text' style="display: none" name='student_id' value="<?php echo $profile[0]['student_id']?>"/>
<button class="btn btn-default" id="changeprofile" type="submit">Wijzigingen opslaan</button>
</form>
As you can see there is also a image upload
this is my controller:
function do_upload()
{
$this->load->model("Gids_model",'',true);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['file_name'] = 'profile_picture'.$_SESSION['id'].'.jpg';
$config['overwrite'] = 'TRUE';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error_upload = array('error' => $this->upload->display_errors());
redirect('Gids/datum', $error_upload);
}
else
{
$this->Gids_model->update_profile($this->input->post('student_id'), $this->input->post('voornaam'), $this->input->post('naam'), $this->input->post('email'), $this->input->post('wachtwoord'), $this->input->post('opleiding'), $this->input->post('school'), $this->input->post('over'), $this->input->post('image'), $this->input->post('gebruikersnaam'));
//$e = $this->input->post('student_id');
$data_upload = array('upload_data' => $this->upload->data());
redirect('Gids/datum', $data_upload);
}
}
And this is my model:
public function update_profile($id, $voornaam, $naam, $email, $wachtwoord, $opleiding, $school, $over, $image, $gebruikersnaam){
$data = array(
'student_id' => $id,
'voornaam' => $voornaam,
'naam' => $naam,
'email' => $email,
'wachtwoord' => $wachtwoord,
'opleiding' => $opleiding,
'school' => $school,
'over' => $over,
'image' => $image,
'gebruikersnaam' => $gebruikersnaam
);
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
}
Could you please help me out.
Also I don't know what the form_open_multipart('Gids/do_upload') is for, I got it from a tutorial to upload images with codeigniter.
Here is what i tried
public function do_upload() {
$this->load->model("Gids_model",'',true);
// load library or you can do it with autoloading
// feature of CI
$this->load->library('upload');
// make sure that the folder uploads is created
// at the root directory of the project
$config = array(
'upload_path' => './uploads',
'allowed_types' => 'jpg|jpeg|JPG|JPEG|png',
'max_size' => '1000',
'file_name' => 'profile_picture.jpg',
'overwrite' => true
);
// use initialize instead
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error_upload = array('error' => $this->upload->display_errors());
// you can check the errors here by using var_dump();
// just uncomment the the line below
// var_dump($this->upload->display_errors());die();
redirect('Gids/datum', $error_upload);
}
else
{
$this->Gids_model->update_profile($this->input->post('student_id'), $this->input->post('voornaam'), $this->input->post('naam'), $this->input->post('email'), $this->input->post('wachtwoord'), $this->input->post('opleiding'), $this->input->post('school'), $this->input->post('over'), $this->input->post('image'), $this->input->post('gebruikersnaam'));
//$e = $this->input->post('student_id');
$data_upload = array('upload_data' => $this->upload->data());
redirect('Gids/datum', $data_upload);
}
}
I tried this and hope it helps:
Controller :
public function upload_profile() {
$input = $this->input->post();
$config['upload_path'] = './uploads/profile_pics/'; //path were I save the uploaded profile pics
$config['allowed_types'] = 'gif|jpg|png'; // allowed types that is mention
//size of the picture by default
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = true;
$this->load->library('upload', $config);
// display error if the picture is not on the config (sample bmp)
if ( ! $this->upload->do_upload())
{
$error = $this->upload->display_errors(); // display the errors
$data['upload_error'] = $error;
if($this->session->userdata('account_id') != null) { // if there is an account
$this->load->model('profile'); //model
$this->load->model('account'); //model
$data['user'] = $this->profile->get_profile($this->session->userdata('account_id')); //get_profile is a function in model
$data['account'] = $this->account->get_account($this->session->userdata('account_id')); //get_account is a function in model
$data['view'] = 'users/settings';
$data['title'] = "User's Settings";
$data['error'] = $error;
$this->load->view('masterpage', $data);
} else {
redirect(base_url('index.php/qablog/login'));
}
}
else
{
//if no error
$data = $this->upload->data();
$updateProfile = array(
'profile_pic' => $data['file_name']
);
$this->load->model('profile');
$this->profile->update_profile($this->session->userdata('account_id'), $updateProfile); // update the profile of the user
redirect(base_url('index.php/users/profile'));
}
}
Model get_profile():
public function get_profile($profile_id)
{
$this->db->select()->from('profile_tbl')->where('profile_id', $profile_id);
$query = $this->db->get();
return $query->first_row('array');
}
Model update_profile():
public function update_profile($profile_id, $data)
{
$this->db->where('profile_id', $profile_id);
$this->db->update('profile_tbl', $data);
return $this->db->affected_rows();
}
Model get_account():
public function get_account($account_id)
{
$this->db->select()->from('account_tbl');
$this->db->where('account_id', $account_id);
$query = $this->db->get();
return $query->result_array();
}
View :
//if there is an error
<?php
if ($error == 3) {?>
<div class="alert alert-success">
×
<strong>Success!</strong> Account or Profile Changed Successfully.
</div>
<?php } else if ($error == 1) { ?>
<div class="alert alert-warning">
×
<strong>Warning!</strong>Password Entered is Incorrect!.
</div>
<?php }else if ($error == 2) { ?>
<div class="alert alert-warning">
×
<strong>Warning!</strong>New Password and Confirm Password!.
</div>
<?php }?>
// default.png if haven't uploaded profile picture
<?php $profilePic = "default.png"; ?>
// if already uploaded profile picture it will display
<?php if($user['profile_pic'] != null) { ?>
<?php $profilePic = $user['profile_pic']; ?>
<?php } ?>
// if there is an error in uploading
<?php if(isset($upload_error)) { ?>
<div class="col-lg-12">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Uploading profile image could not be completed. <?php print_r($upload_error); ?>
</div>
</div>
<?php } ?>
<div class="col-lg-12">
//display the profile picture
<img src="<?php echo base_url('uploads/profile_pics/'.$profilePic); ?>" width="100" />
// call the controller upload_profile
<?php echo form_open_multipart(base_url('index.php/users/upload_profile'));?>
<input type="file" name="userfile" id="userfile" size="20" style="display:none;" />
<label for="userfile" class="btn btn-info btn-sm">Choose Image</label>
<input type="submit" class="btn btn-xs" value="edit profile" />
</form>
<h3 class="text-info"><?php echo $user['fname'].' '.$user['lname']; ?></h3>
</div>
Just follow this, and if you have problem just tell me. :)
in my CodeIgniter project I'm uploading files during the project creation. Here's the uploading function:
public function addProcess()
{
echo 'test';
if($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('album', 'Album', 'trim|required|callback_check_select', 'xss_clean');
if ($this->form_validation->run() === FALSE)
{
$data['albums'] = $this->album_model->albumList();
$this->adminTheme('admin/addSong',$data);
}
else
{
$error = 0;
$this->load->library('upload');
$total_count_of_files = count($_FILES['userfile']['name']);
$album = $this->input->post('album');
$songs = $this->input->post('song');
$artist = $this->input->post('artist');
for($i=0; $i< $total_count_of_files; $i++)
{
if(!$songs[$i])
$songs[$i] = "Track-".($i+1);
if(!$artist[$i])
$artist[$i] = " ";
$_FILES['file']['name'] = $_FILES['userfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['userfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['userfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['userfile']['size'][$i];
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|gif|png|mp3';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if($this->upload->do_upload('file'))
{
$msg = $this->upload->data();
$name = $msg['file_name'];
$error += 0;
$this->song_model->add($songs[$i], $artist[$i], $name, $album);
}else{
$errorStr[] = "$songs[$i] Upload Faild";
$error += 1;
}
}
//$this->album_model->add();
if($error == 0)
{
//$this->msg('admin/song','Successfully added..Redirecting now...');
}
else
{
$this->msg('admin/song','Successfully added..Redirecting now...');
}
}
}
else
{
redirect('admin/album');
}
}
another function for doupload
public function do_upload()
{
$upload_path_url = base_url().'uploads/';
$config['upload_path'] = FCPATH.'uploads/';
$config['allowed_types'] = 'jpg|jpeg|gif|png|mp3';
$config['max_size'] = '30000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload', $error);
} else {
$data = $this->upload->data();
$info->name = $data['file_name'];
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $upload_path_url .$data['file_name'];
$info->thumbnail_url = $upload_path_url .$data['file_name'];
$info->delete_url = base_url().'upload/deleteImage/'.$data['file_name'];
$info->delete_type = 'DELETE';
if (IS_AJAX) {
echo json_encode(array($info));
} else {
$file_data['upload_data'] = $this->upload->data();
$this->load->view('admin/upload_success', $file_data);
}
}
}
my form code
<div id="container">
<h2>Song Name - Add New</h2>
<div class="error">
<?php echo validation_errors(); ?>
</div>
<?php $attributes = array('id' => 'myform'); ?>
<?php echo form_open_multipart('admin/song/addProcess',$attributes); ?>
<div class="line">
<label style="width: 160px;">Album:</label>
<select class="category" name="album" style="width: 280px;">
<option value="select">Select Album</option>
<?php foreach($albums as $album): ?>
<option value="<?php echo $album['id']; ?>">
<?php echo $album['root_name']." --> ".$album['category_name']." --> ".$album['album_name']; ?></option>
<?php endforeach ?>
</select>
<input class="form-submit" style="margin-top: 6px;" type="button" id="more_fields" onclick="add_fields();" value="Add More" />
</div>
<!--end line-->
<div id="nameFields">
<div class="line">
<input type="text" name="song[]" class="input1" style="width: 180px;" placeholder="Song Name" />
<input type="text" name="artist[]" class="input1" style="width: 180px;" placeholder="Artist Name" />
<input type="file" name="userfile[]" class="category" style="width:80px;" />
</div>
<!--end line-->
</div>
<input type="submit" value="Save" class="form-submit" style="margin-right: 180px;" />
</form>
</div>
<!--end container-->
<script type="text/javascript">
function add_fields() {
document.getElementById('nameFields').innerHTML += "<div class='line'><input type='text' name='song[]' class='input1' style='width: 180px;' placeholder='Song Name' /><input type='text' name='artist[]' class='input1' style='width: 180px;' placeholder='Artist Name' /><input type='file' name='userfile[]' class='category' style='width:80px;' /></div>";
}
</script>
However this does not do anything. The files are not being uploaded. Even an empty directory is not being created. Could anybody help me to find the error?
Thanks.
In your addProcess code, remove below code
$_FILES['file']['name'] = $_FILES['userfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['userfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['userfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['userfile']['size'][$i];
and try
foreach ($_FILES as $fieldname => $fileObject)
{
if (!empty($fileObject['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($fieldname))
{
$errors[] = $this->upload->display_errors();
}
else
{
//success code
}
}
}