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'];
}
Related
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.
I am trying to get users details from the database and put it in session so that it can be used in the view. I have tried all I can but I keep getting error. Undefined Variable Email.
MODEL:
function login($username, $password)
{
$this->db->select('authTbl.id, authTbl.password, authTbl.username, authTbl.email, authTbl.mobile');
$this->db->from('users as authTbl');
$this->db->where('authTbl.username', $username);
$this->db->where('authTbl.isDeleted', 0);
$query = $this->db->get();
$user = $query->result();
if(!empty($user)){
if(verifyHashedPassword($password, $user[0]->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
CONTROLLER:
function isLoggedIn()
{
$isLoggedIn = $this->session->userdata('isLoggedIn');
$data['title'] = 'Login';
if(!isset($isLoggedIn) || $isLoggedIn != TRUE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
redirect('posts');
}
}
/**
* This function used to logged in user
*/
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Login';
$this->form_validation->set_rules('username', 'Username', 'required|max_length[128]|trim');
//$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]|');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->user_model->login($username, $password);
if(count($result) > 0)
{
foreach ($result as $res)
{
$sessionArray = array('id'=>$res->id,
'username'=>$res->username,
'email'=>$res->email,
'mobile'=>$res->mobile,
'isLoggedIn' => TRUE
);
$this->session->set_userdata($sessionArray);
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
}
}
else
{
$this->session->set_flashdata('login_fail', 'Email or password mismatch');
redirect('users/login');
}
}
}
VIEW:
<?php echo $email; ?>
You are creating the session for user information
Try to fetch the session data :
echo $this->session->userdata('email');
or trying to pass the data in views $data
$email will not work because writing $email means ordinary variable but in your case you have to write like :
<?php echo $this->session->userdata('email'); ?>
If You are using flashdata, then You can get it using below code:
Controller
if (empty($this->session->userdata('UserID'))) {
$this->session->set_flashdata('flash_data', 'You don\'t have access!');
$this->load->view("initialHeader");
$this->load->view("login");
redirect('Login');
}
View
<?php if(!empty($this->session->flashdata('flash_data'))) {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('flash_data'); ?>
</div>
<?php } ?>
If You are using tmp data as a session, please refer below code:
Controller
<?php
if (!empty($data)) {
$this->session->set_userdata('permission_error_msg', $data);
$this->session->mark_as_temp('permission_error_msg', 10); // For 10 Seconds
$this->load->view('dashboard', array($title, $data));
} ?>
View
<?php if ($this->session->tempdata('permission_error_msg')) { ?>
<b class="login_error_msg"><?php
if (!empty($this->session->tempdata('permission_error_msg'))) {
echo $this->session->tempdata('permission_error_msg');
}
?></b>
<?php } ?>
Thank You.
When I use only 1 controller in my application, user, everything works fine. When I try to use 2 or 3 to divide the code and create some structure my application always give the following error :
A PHP Error was encountered
Severity: Warning
Message: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php:99)
Filename: Session/Session.php
Line Number: 140
Backtrace:
File: /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php
Line: 11
Function: __construct
File: /Applications/MAMP/htdocs/BT_dashboard/index.php
Line: 292
Function: require_once
Googled it and tried many things but can't find an answer. I'm using codeigniter 3. My User controller looks like :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User class.
*
* #extends CI_Controller
*/
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
$this->load->model('project_model');
}
public function createProject() {
if ($_SESSION['userlevel']) {
if ($_SESSION['userlevel'] < 3) {
$userid = $this->uri->segment(3);
} else {
$userid = $this->input->post('userproject');
}
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('project_name', 'project name', 'trim|required|min_length[2]|callback_is_project_name_unique[' . $this->input->post('project_name') . ']');
$this->form_validation->set_rules('project_address', 'project address', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_description', 'project description', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_city', 'project city', 'trim|required|min_length[2]');
if ($this->form_validation->run() == FALSE) {
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
if ($_SESSION['userlevel'] < 3) {
$this->load->view('dashboard_add_project', $data);
} else {
$data['userslist'] = $this->user_model->get_users_list();
$this->load->view('dashboard_add_project_admin', $data);
}
$this->load->view('wrapper', $data);
} else {
$Address = urlencode($this->input->post('project_address'));
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" . $Address . "&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status == "OK") {
$Lat = $xml->result->geometry->location->lat;
$Lon = $xml->result->geometry->location->lng;
$LatLng = "$Lat,$Lon";
}
//pass validation
$data = array(
'project_name' => $this->input->post('project_name'),
'project_address' => $this->input->post('project_address'),
'project_description' => $this->input->post('project_description'),
'project_city' => $this->input->post('project_city'),
'project_finished' => $this->input->post('project_finished'),
'lat' => $Lat,
'lng' => $Lon,
);
//$this->db->insert('tbl_user', $data);
if ($this->user_model->create_project($data, $userid, $this->input->post('project_name'))) {
if ($_SESSION['userlevel'] > 1) {
$data['projectlist'] = $this->user_model->get_project_list();
$data['uncompleted_projects'] = $this->user_model->get_uncompleted_projects();
$data['completed_projects'] = $this->user_model->get_completed_projects();
} else {
$data['projectlist'] = $this->user_model->get_project_list_userid($userid);
}
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
$this->load->view('dashboard_projects', $data);
$this->load->view('wrapper', $data);
} else {
$data->error = 'There was a problem creating your new employee. Please try again.';
$data['userdata'] = $this->session->userdata;
// send error to the view
$this->load->view('header', $data);
$this->load->view('dashboard_add_project', $data);
$this->load->view('wrapper', $data);
}
}
}
}
My second controller, the project controller. This is the controller I want to use know to paste the createproject code so this gives more structure. But when I paste it here and adapt my views it gives the error. here's my project_controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
* File Name: employee.php
*/
class Project extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
}
public function createProject() {
//same as usercontroller
My User/login code in User controller :
public function login() {
$loggedin = $this->session->userdata('logged_in');
if (!$loggedin) {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('user_mail', 'user mail', 'required');
$this->form_validation->set_rules('user_password', 'user password', 'required');
if ($this->form_validation->run() == false) {
$data = new stdClass();
$data->error = 'Check your user and password';
$this->load->view('dashboard_login', $data);
} else {
$usermail = $this->input->post('user_mail');
$password = $this->input->post('user_password');
if ($this->user_model->resolve_user_login($usermail, $password)) {
$user_id = $this->user_model->get_user_id_from_mail($usermail);
$user = $this->user_model->get_user($user_id);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = (string) $user->user_name;
$_SESSION['logged_in'] = (bool) true;
$_SESSION['user_gsm'] = (string) $user->user_gsm;
$_SESSION['user_address'] = (string) $user->user_address;
$_SESSION['user_city'] = (string) $user->user_city;
$_SESSION['userlevel'] = $this->user_model->get_user_level((int) $user->user_id);
$_SESSION['user_mail'] = $usermail;
$data['userdata'] = $this->session->userdata;
if ($_SESSION['userlevel'] == "3") {
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
}
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
} else {
$data = new stdClass();
// login failed
$data->error = 'Wrong username or password.';
// send error to the view
$this->load->view('dashboard_login', $data);
}
}
} else {
$data['userdata'] = $this->session->userdata;
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
}
}
In config/autoload I've got following:
$autoload['libraries'] = array('database','session');
So, what is on line 99 in your Project.php controller?
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'/>