Hi guys I am new to Codeigniter and new to the MVC webdesign, and I've been trying to implement this image upload into my registration form with no success.
In another page where the user edits his profile i've added it successfully but for the life of me i can't add it to this register form. It's not uploading to my database or to my server
Here is what I've tried:
//upload controller
public function do_upload() {
$user = $this->ion_auth->user()->row();
$config['upload_path'] = './some/folder/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 2000;
$config['overwrite'] = TRUE;
$current_user_id = $user->id;
$current_user_username = $user->username;
$config['file_name'] = $current_user_id . "_" . $current_user_username;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
redirect('/', 'refresh');
}
else {
$vars['user'] = $user;
$current_user = $user->id;
$vars['recent_messages'] = $this->ss_messages_model->find_all_array(array('id_user' => $user->id), 'date_added desc', 5);
$image_data = $this->upload->data();
$data = array('userfile' => $image_data['file_name']);
$this->ion_auth->update($user->id, $data);
}
}
//register function in the auth controller
function register()
{
$this->data['title'] = "Register User";
$this->data['lang'] = $this->clang;
**$this->do_upload();**
$tables = $this->config->item('tables','ion_auth');
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('register_fname'), 'alpha_space|required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('register_user_validation_lname_label'), 'alpha_space|required|xss_clean');
if ($this->form_validation->run() == true)
{
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = strtolower($this->input->post('email'));
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
**'userfile' => $this->input->post('userfile');**
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
{
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
$this->_render_page("auth/_success");
}
else
{
//display the register user form
//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')));
$this->data['image']= $this->_create_captcha();
$this->_render_page('auth/register', $this->data);
}
}
**//view**
<div class="input-box">
<div class="agent-lable"><?php echo "Picture: (jpg or png)"; ?>
</div><br>
<input type = "file" name = "userfile" size = "20" />
</div>
You need to realize a few things:
At the start of the registration function where you call do_upload the user isn't created yet. As you want to add an image for the user, you need to wait until the IonAuth register function adds them to the database.
$this->ion_auth->user()->row() when the user id isn't specified gets the row of the current user: "If a user id is not passed the id of the currently logged in user will be used." As nobody is logged in yet $user->username will be null and $user->id in the update function will also be null - hence it is not updating; and if it did, it wouldn't be for the correct user!
You should modifiy your register function like so:
function register() {
echo 'register function triggered <br>';
$this->data['title'] = "Register User";
$this->data['lang'] = $this->clang;
//$this->do_upload(); User isn't created yet!!
//$tables = $this->config->item('tables', 'ion_auth');
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('register_fname'), 'alpha_space|required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('register_user_validation_lname_label'), 'alpha_space|required|xss_clean');
if ($this->form_validation->run()) {
echo 'form validation passed <br>';
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = strtolower($this->input->post('email'));
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
//'userfile' => $this->input->post('userfile') files are not in $_POST array
);
$register = $this->ion_auth->register($username, $password, $email, $additional_data);
if ($register) {
echo 'user successfully registered <br>';
print_r($register);
/**
* The user is already registered here... If the upload function fails, we should let
* them know somewhere else other than the register form as this hasn't affected
* their registration
*/
$upload = $this->do_upload($register);
if ($upload !== true) {
$this->session->set_flashdata('message', $upload);
}
$this->session->set_flashdata('message', $this->ion_auth->messages());
$this->_render_page("auth/_success");
} else {
$this->data['message'] = $this->ion_auth->errors();
$this->data['image'] = $this->_create_captcha();
$this->_render_page('auth/register', $this->data);
}
} else {
$this->data['message'] = validation_errors();
$this->data['image'] = $this->_create_captcha();
$this->_render_page('auth/register', $this->data);
}
}
and your do_upload function to accept the newly created user id as a parameter:
public function do_upload($uid) {
// added new users uid
$user = $this->ion_auth->user($uid)->row();
$config['upload_path'] = './some/folder/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 2000;
$config['overwrite'] = TRUE;
$current_user_id = $user->id;
$current_user_username = $user->username;
$config['file_name'] = $current_user_id . "_" . $current_user_username;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo '<br> upload errors <br>';
exit($this->upload->display_errors());
return $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
//redirect('/', 'refresh');
} else {
echo 'upload success <br>';
// variables unused in scope
//$vars['user'] = $user;
//$current_user = $user->id;
//$vars['recent_messages'] = $this->ss_messages_model->find_all_array(array('id_user' => $user->id), 'date_added desc', 5);
$image_data = $this->upload->data();
$data = array('userfile' => $image_data['file_name']);
$this->ion_auth->update($user->id, $data);
return true;
}
}
It is important to note. Even if for some reason the upload function fails, we shouldn't re-show the register form... the user is already registered (remember, we needed their id). Instead redirect them to the success page and just say hey, we couldn't upload your profile picture.
If your profile picture is required I would suggest to validate that it exists before continuing with the register function, so like before form validation.
If you didn't want the username and user id to for the image name there is another option than this code that is cleaner.
Related
I'm making a form where the person could add a picture in it and it will show in a local directory folder and show up in sql table. But it seems that how many times that I tried the picture I tried uploading wont upload! Please help!
Controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Auth extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->database();
$this->load->library('session');
$this->load->library(array('ion_auth', 'form_validation'));
$this->load->helper(array('url', 'language', 'form'));
$this->load->model('Ion_auth_model');
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
log_message('debug', 'CI My Admin : Auth class loaded');
}
public function index() {
$data['page'] = $this->config->item('englishlivebali_template_dir_public') . "login_form";
$data['module'] = 'auth';
$this->load->view($this->_container, $data);
}
public function login_form(){
if ($this->ion_auth->logged_in()) {
redirect('student', 'refresh');
} else {
$data['page'] = $this->config->item('englishlivebali_template_dir_public') . "login_form";
$data['module'] = 'auth';
$this->load->view($this->_container, $data);
}
}
public function login_formteacher(){
if ($this->ion_auth->logged_in()) {
redirect('teacher', 'refresh');
} else {
$data['page'] = $this->config->item('englishlivebali_template_dir_public') . "login_formteacher";
$data['module'] = 'auth';
$this->load->view($this->_container, $data);
}
}
public function login() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true) {
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember)) {
if ($this->input->post('username')=='teacher') {
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/teacher/dashboard', 'refresh');
}
elseif ($this->input->post('username')!=='teacher') {
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/student/index', 'refresh');
}
else {
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/student/dashboard', 'refresh');
}
} else {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login_form', 'refresh');
}
}
}
public function logout() {
$this->ion_auth->logout();
redirect('auth', 'refresh');
}
/* End of file auth.php */
/* Location: ./modules/auth/controllers/auth.php */
public function users_save()
{
$username = $_POST["username"];
$email = $_POST["email"];
$salt = $this->Ion_auth_model->store_salt ? $this->Ion_auth_model->salt() : FALSE;
$password = $this->Ion_auth_model->hash_password($_POST["password"], $salt);
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run()===FALSE)
{
$this->session->set_flashdata('gagal_user_save', 'Gagal Menambahkan User Baru');
redirect('auth');
}
else {
$this->db->query("INSERT INTO users (username, email, password, active) values ('$username', '$email', '$password', 1)");
$idn = $this->db->query("select id from users order by id desc limit 1")->result();
foreach ($idn as $val => $value ){
$idValue = $value->id;
}
$this->db->query("insert into users_groups (user_id, group_id) values ('$idValue','$idgz')");
$this->session->set_flashdata('sukses_user_save', 'Sign Up Success, Now Please Log In');
redirect ('auth');
}
}
public function biodata()
{
$namad = $_POST["namad"];
$namab = $_POST["namab"];
$tempat_lahir = $_POST["tempat_lahir"];
$tgl_lahir = $_POST["tgl_lahir"];
$jk = $_POST["jk"];
$agama = $_POST["agama"];
$ayah = $_POST["ayah"];
$ibu = $_POST["ibu"];
$alamat = $_POST["alamat"];
$idz = $this->input->post('up');
$this->db->query("UPDATE users SET first_name = '$namad', last_name = '$namab', tempat_lahir = '$tempat_lahir', tgl_lahir = '$tgl_lahir', jk = '$jk', agama = '$agama', ayah = '$ayah', ibu = '$ibu', alamat = '$alamat' WHERE id = '$idz'");
redirect ('student/biodata');
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
redirect ('student/biodata');
}else{
$file_data = $this->upload->data();
$data['img'] = base_url().'/uploads/'.$file_data['file_name'];
}
}
}
The Input Type in the form has an ID of "gambar_produk" and also has a name of "gambar_produk". The function that I am trying to use is the do_upload function. I tried searching for various ways but it still won't work. Please help!
Hope this will help you :
Note : your form should have attribute enctype="multipart/form-data",
better use form_open_multipart();
Relace $this->upload->do_upload() with $this->upload->do_upload('gambar_produk'), where gambar_produk is the name of file input
Your method do_upload should be like this :
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('gambar_produk'))
{
$error = array('error' => $this->upload->display_errors());
redirect ('student/biodata');
}else
{
$file_data = $this->upload->data();
$data['img'] = base_url().'/uploads/'.$file_data['file_name'];
}
}
For more : https://www.codeigniter.com/userguide3/libraries/file_uploading.html
By default do_upload expects the file to come from a form field called userfile, and the form must be of type “multipart”.
To make-it works, please change the name of the input file gambar_produk to userfile or use
if ( ! $this->upload->do_upload('gambar_produk'))
{
$error = array('error' => $this->upload->display_errors());
redirect ('student/biodata');
}else{
$file_data = $this->upload->data();
$data['img'] = base_url().'/uploads/'.$file_data['file_name'];
}
I need the image to save to the session:
Here is my code so far:
Model:
function ProfileImages()
{
parent::__construct();
}
function exists($username)
{
$this->db->select('*')->from("profileimages")->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return true;
/*
echo "user $user exists!";
$row = $query->row();
echo " and his profileimage is $row->profileimage";
*/
}
else
{
return false;
//echo "no such user as $user!";
}
}
function putProfileImage($username, $img)
{
$record = array('user' => $username, 'profileimage' => $img);
if ($this->exists($username))
{
$this->db->where('user', $username)->update('profileimages', $record);
}
else
{
$this->db->where('user', $username)->insert('profileimages', $record);
}
}
function getProfileImage($username)
{
$this->db->select('*')->from('profileimages')->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0){
$row = $query->row();
return $row->profileimage;
}
return "";
}
}
Controller:
function __construct()
{
// Call the parent construct
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
}
function upload()
{
$config = array(
'allowed_types' =>'gif|jpg|jpeg|png',
'upload_path' =>'./web-project-jb/assets/puploads/',
'max_size' => 10000,
'max_width' => 1024,
'max_height' => 768);
$this->load->library('upload', $config);
$img = $this->session->userdata('img');
$username = $this->session->userdata('username');
//fail show upload form
if (! $this->upload->do_upload())
{
$error = array('error'=>$this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $error, $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
else
{
//successful upload so save to database
$file_data = $this->upload->data();
$img = $file_data['file_name'];
$data['img'] = '/web-project-jb/assets/puploads/'.$file_data['file_name'];
// you may want to delete the image from the server after saving it to db
// check to make sure $data['full_path'] is a valid path
// get upload_sucess.php from link above
//$image = chunk_split( base64_encode( file_get_contents( $data['file_name'] ) ) );
$this->img = $this->session->userdata('img');
$this->username = $this->session->userdata('username');
$this->profileimages->putProfileImage($username, $img);
$data['username'] = $username;
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$username = $this->session->userdata('username');
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $data, $viewData);
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
}
function index()
{
$username = $this->session->userdata('username');
$data['username'] = $username;
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
//$this->load->view('homeprofile/upload_form', $data);
$this->load->view('homeprofile/homeprofileview', $data, $viewData, array('error' => ' ' ) );
$this->load->view('shared/footer');
}
}
View:
<h3><?="Profile Image"?></h3>
<img src="<?php if (isset($img)) echo base_url($img); ?>"
width='300' height='300'/>
<?=form_open_multipart('homeprofile/upload');?>
<input type="file" name="userfile" value=""/>
<?=form_submit('submit', 'upload')?>
<?=form_close();?>
<?php if (isset($error)) echo $error;?>
</div>
</div>
I'm thinking would I actually be needing to save the image as a link into my database as opposed to the file name? the get profileimage function is meant to throw the image back to the screen so that it stays there. Once again thanks for all your help.
This line is the problem:
$this->profileimages->putProfileImage($username, $img);
You are saving the image, but not the path. So as you've said you need to save the actual path:
$img = '/web-project-jb/assets/puploads/'.$file_data['file_name'];
...etc
$this->profileimages->putProfileImage($username, $img);
Hopefully this should help you solve the issue you have.
EDIT
About the session try to do something like:
$this->session->set_userdata($img); //note I've changed the name above as well.
Check codeigniter session class guide for further references.
Hi guys I have recently managed to get images to upload to my profile page but when I refresh the page the image disappears. I think this is because how the image is being put into the db.
Here is model:
function ProfileImages()
{
parent::__construct();
}
function exists($username)
{
$this->db->select('*')->from("profileimages")->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return true;
/*
echo "user $user exists!";
$row = $query->row();
echo " and his profileimage is $row->profileimage";
*/
}
else
{
return false;
//echo "no such user as $user!";
}
}
function putProfileImage($username, $img)
{
$record = array('user' => $username, 'profileimage' => $img);
if ($this->exists($username))
{
$this->db->where('user', $username)->update('profileimages', $record);
}
else
{
$this->db->where('user', $username)->insert('profileimages', $record);
}
}
function getProfileImage($username)
{
$this->db->select('*')->from('profileimages')->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0){
$row = $query->row();
return $row->profileimage;
}
return Null;
}
}
Here is my controller:
class HomeProfile extends CI_Controller
{
function HomeProfile()
{
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
}
function upload()
{
$config = array(
'allowed_types' =>'gif|jpg|jpeg|png',
'upload_path' =>'./web-project-jb/assets/puploads/',
'max_size' => 10000,
'max_width' => 1024,
'max_height' => 768
);
$this->load->library('upload', $config);
$img = $this->session->userdata('img');
$username = $this->session->userdata('username');
$this->profileimages->putProfileImage($username, $this->input->post("profileimage"));
//fail show upload form
if (! $this->upload->do_upload())
{
$error = array('error'=>$this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $error, $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
else
{
//successful upload so save to database
$file_data = $this->upload->data();
$data['img'] = '/web-project-jb/assets/puploads/'.$file_data['file_name'];
// you may want to delete the image from the server after saving it to db
// check to make sure $data['full_path'] is a valid path
// get upload_sucess.php from link above
//$image = chunk_split( base64_encode( file_get_contents( $data['file_name'] ) ) );
$this->username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$username = $this->session->userdata('username');
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $data, $viewData);
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
}
function index()
{
$username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
//$this->load->view('homeprofile/upload_form', $data);
$this->load->view('homeprofile/homeprofileview', $data, $viewData, array('error' => ' ' ) );
$this->load->view('shared/footer');
}
}
If you look at the putprofileimages function in the model I'm think I would put an appends command in here somewhere. I want the filename of the image to appear in the db in the profileimage field. Also Im hoping the profile image will stay on the screen when I refresh
<h3><?="Profile Image"?></h3>
<img src="<?php if (isset($img)) echo base_url($img); ?>" width='300' height='300'/>
<?=form_open_multipart('homeprofile/upload');?>
<input type="file" name="userfile" value=""/>
<?=form_submit('submit', 'upload')?>
<?=form_close();?>
<?php if (isset($error)) echo $error;?>
</div>
</div>
<div id="secondary">
<p>
<?=$profileText;?>
</p>
<p>
<?=form_open('homeprofile/changetext'); ?>
<?php $msgbox = array(
'name' => 'profiletext',
'rows' => '8',
'cols' => '30',
);?>
<?=form_textarea($msgbox);?>
</p>
<p>
<?=form_submit('submit', 'Change'); ?>
<?=form_close(); ?>
</p>
</div>
You can simply save just the image name in the db like a char field.
Just after your do_upload function you can retrieve the image name with $this->upload->file_name
Then you can easly save this in the db, not the whole file.
In your view page now you can set via html the image path and then appen just the file name you get from the db query.
One quick note - are you using codeigniter 2 ?
you should set up your constructors this way:
class HomeProfile extends CI_Controller
{
function __construct()
{
// Call the parent construct
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
} // end construct
And its the same for the models!
ok in yr model, maybe i'm not getting this but you have
if ($this->exists($username))
but your method says
function putProfileImage($username, $img)
so if username might be blank, you need to just set a default like
function putProfileImage($username = 0, $img)
then maybe you could do
if ($username === 0)
but personally i would not put insert and update in the same method, split them up,
will be much easier to debug.
also -- Did you load the session library in autoload???
I'm creating a profile page where when I select an image to upload it will be stored in the uploads folder but will not display to the screen - why would this be.
The container of an image seems to appear, but not the image
But the upload function does correctly thtow back an error if I don't select an image to upload
Here is my controller with the upload feature within it - i realise the folder is called puploads:
class HomeProfile extends CI_Controller
{
function HomeProfile()
{
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
}
function upload()
{
$config = array(
'allowed_types' =>'gif|jpg|jpeg|png',
'upload_path' =>'./web-project-jb/assets/puploads/',
'max_size' => 10000,
'max_width' => 1024,
'max_height' => 768
);
$this->load->library('upload', $config);
$img = $this->session->userdata('img');
$username = $this->session->userdata('username');
$this->profileimages->putProfileImage($username, $this->input->post("profileimage"));
//fail show upload form
if (! $this->upload->do_upload())
{
$error = array('error'=>$this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $error, $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
else
{
//successful upload so save to database
$file_data = $this->upload->data();
$data['img'] = base_url().'./web-project-jb/assets/puploads/'.$file_data['file_name'];
// you may want to delete the image from the server after saving it to db
// check to make sure $data['full_path'] is a valid path
// get upload_sucess.php from link above
//$image = chunk_split( base64_encode( file_get_contents( $data['file_name'] ) ) );
$this->username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$username = $this->session->userdata('username');
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $data, $viewData);
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
}
function index()
{
$username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
//$this->load->view('homeprofile/upload_form', $data);
$this->load->view('homeprofile/homeprofileview', $data, $viewData, array('error' => ' ' ) );
$this->load->view('shared/footer');
}
}
Here is my profileimages model:
function ProfileImages()
{
parent::__construct();
}
function exists($username)
{
$this->db->select('*')->from("profileimages")->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return true;
/*
echo "user $user exists!";
$row = $query->row();
echo " and his profileimage is $row->profileimage";
*/
}
else
{
return false;
//echo "no such user as $user!";
}
}
function putProfileImage($username, $img)
{
$record = array('user' => $username, 'profileimage' => $img);
if ($this->exists($username))
{
$this->db->where('user', $username)->update('profileimages', /*'./uploads/.' */$record);
//appends
}
else
{
$this->db->where('user', $username)->insert('profileimages', $record);
}
}
function getProfileImage($username)
{
$this->db->select('*')->from('profileimages')->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0){
$row = $query->row();
return $row->profileimage;
}
return Null;
}
}
Here is my view:
<h3><?="Profile Image"?></h3>
<img src="./web-project-jb/assets/puploads/" width='300' height='300'/>
<?=form_open_multipart('homeprofile/upload');?>
<input type="file" name="userfile" value=""/>
<?=form_submit('submit', 'upload')?>
<?=form_close();?>
<?php if (isset($error)) echo $error;?>
</div>
</div>
I have tried replacing the img src with but I just get an error back saying data is unrecognised
Your view file does not indicate any attempt to output a dynamic image, you have the src hardcoded and aren't using your $img variable at all (the one you set in the controller with $data['img']):
$data['img'] = base_url().'./web-project-jb/assets/puploads/'.$file_data['file_name'];
Here also you seem to be mixing server paths and URLs. Assuming the URL to your uploads folder is:
http://example.com/web-project-jb/assets/puploads/
...use this in your controller (after the upload succeeds):
$data['img'] = 'web-project-jb/assets/puploads/'.$file_data['file_name'];
Then in your view:
<img src="<?php echo base_url($img); ?>" width='300' height='300'/>
I've had a few questions about this issue already but I keep end up not really making much progress. I'm trying to upload an image onto a page and have the filename appear in the database beside the users name but it keeps appearing a zero. Why would this be? The image field is a varchar so it will save the filename. But since I then want my getProfileImage function to display the image back to the screen, should it be a blob?
Here is my controller:
function __construct()
{
// Call the parent construct
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
}
function upload()
{
$config = array(
'allowed_types' =>'gif|jpg|jpeg|png',
'upload_path' =>'./web-project-jb/assets/puploads/',
'max_size' => 10000,
'max_width' => 1024,
'max_height' => 768
);
$this->load->library('upload', $config);
$img = $this->session->userdata('img');
$username = $this->session->userdata('username');
//fail show upload form
if (! $this->upload->do_upload())
{
$error = array('error'=>$this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $error, $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
else
{
//successful upload so save to database, which it doesn't
$file_data = $this->upload->data();
$data['img'] = '/web-project-jb/assets/puploads/'.$file_data['file_name'];
// you may want to delete the image from the server after saving it to db
// check to make sure $data['full_path'] is a valid path
// get upload_sucess.php from link above
//$image = chunk_split( base64_encode( file_get_contents( $data['file_name'] ) ) );
$this->username = $this->session->userdata('username');
$this->profileimages->putProfileImage($username, $img);
$data['profileimages'] = $this->profileimages->getProfileImage($username, $img);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$username = $this->session->userdata('username');
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/homeprofileview', $data, $viewData);
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
}
function index()
{
$username = $this->session->userdata('username');
$img = $this->session->userdata('img');
$data['profileimages'] = $this->profileimages->getProfileImage($username, $img);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
//$this->load->view('homeprofile/upload_form', $data);
$this->load->view('homeprofile/homeprofileview', $data, $viewData, array('error' => ' ' ) );
$this->load->view('shared/footer');
}
}
My model:
var $proimage_path;
function ProfileImages()
{
parent::__construct();
$this->proimage_path = 'web-project-jb/assets/puploads';
}
function exists($username)
{
$this->db->select('*')->from("profileimages")->where('user', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return true;
/*
echo "user $user exists!";
$row = $query->row();
echo " and his profileimage is $row->profileimage";
*/
}
else
{
return false;
//echo "no such user as $user!";
}
}
function putProfileImage($username, $img)
{
$record = array('user' => $username, 'profileimage' => $img);
if ($this->exists($username))
{
$this->db->where('user', $username)->update('profileimages', $record);
}
else
{
$this->db->where('user', $username)->insert('profileimages', $record);
}
}
function getProfileImage($img)
{
$this->db->select('*')->from('profileimages')->where('profileimage', $img);
$query = $this->db->get();
if ($query->num_rows() > 0){
$row = $query->row();
return $row->profileimage;
}
return $img;
}
}
Can you please tell me why you reading the file name from session instead of using the uploaded image file name? assuming the user has no image and you set the session when user logs in, would not that be NUll??
in your controller
function upload() {
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/album/';
$config['allowed_types'] = 'jpeg|jpg|png|gif|';
$config['max_size'] = '500000';
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$file = $this->upload->data();
$keterangan = $this->input->post('keterangan');
$this->MGallery->addGallery($file['file_name'], $keterangan);
$this->session->set_flashdata('message', 'Foto <b>' . $file['file_name'] . '</b> berhasil di upload!');
redirect('admin/album/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Foto <b>' . $file['file_name'] . '</b> gagal di upload!');
redirect('admin/album/lihat', 'refresh');
}
} else {
redirect('admin/album/lihat', 'refresh');
}
}
in your model
function addGallery($file_name, $keterangan) {
$now = date("Y-m-d H:i:s");
$data = array(
'foto' => $file_name,
'keterangan' => $keterangan,
'IDKategori' => $this->input->post('kategori'),
'tgl' => $now
);
$this->db->insert('album', $data);
}
and then, in your view like this
<?php
if ($this->session->flashdata('message')) {
echo "<div class='message'>" . $this->session->flashdata('message') . "</div>";
} ?>
<form action="<?= base_url(); ?>admin/album/upload" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<input type="file" name="userfile" size="20" />
</p>
<p>
<select name="kategori">
<?php
foreach ($gallery_cat as $key => $list) {
?>
<option value="<?= $list['IDKategori'] ?>">
<?= $list['kategori'] ?>
</option>
<?php
}
?>
</select>
</p>
<p>
<textarea name="keterangan" cols="40" rows="5"></textarea>
</p>
<p>
<label>
<input type="submit" name="submit" value="Uplaod Foto" />
</label>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
</p>