I'm making a website on the CodeIgniter framework so users can upload products on the website to the database. I'm trying to make a function so users can upload pictures to my database but its not really working.
Here some info:
DB table name: products
The DB table column name that I want the pictures to be stored in: product_foto
picture folder: upload
My controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Controller {
var $data = array();
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
$this->load->helper(array('form', 'url'));
}
public function product_form()
{
$save = array(
'product_naam' => $this->input->post('product_naam'),
'product_beschrijving' => $this->input->post('product_beschrijving'),
'product_categorie' => $this->input->post('product_categorie'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
'product_foto' => $this->input->post('product_foto'),
'date_created' => date('Y-m-d'),
'date_updated' => date('Y-m-d')
);
$this->product_model->saveProduct($save);
redirect('https://kadokado-ferran10.c9users.io/AlleCadeausController');
}
public function upload(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file')){
$this->db->insert('products', array(
'product_foto' => $this->upload->file_name
));
$error = array('error'=>$this->upload->display_errors());
$this->load->view('product_form', $error);
}else{
$file_data = $this->upload->data();
$data['img'] = base_url().'/upload/'.$file_data['file_name'];
header('location:https://kadokado-ferran10.c9users.io/Product/');
}
}
}
My model file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Controller {
var $data = array();
My view file:
<?php echo form_open_multipart('Product/upload'); ?>
<input type="file" name="userfile" />
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<input type="submit" name="submit" value="test" />
</form>
When I submit the form the picture only gets added to the upload folder but it doesn't get added into the database column..
Change your upload() function as follow
public function upload(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile')){
$error = array('error'=>$this->upload->display_errors());
$this->load->view('product_form', $error);
}else{
$file_data = $this->upload->data();
$this->db->insert('products', array(
'product_foto' => $file_data['file_name']
));
$data['img'] = base_url().'/upload/'.$file_data['file_name'];
header('location:https://kadokado-ferran10.c9users.io/Product/');
}
}
Related
I am using following code to upload video in my codeigniter project.
This is my view code
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<input type="submit" value="upload" />
</form>
This is controller
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|mp4';
$config['max_size'] = 100000;
$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());
var_dump($error);
}
else
$data = array('upload_data' => $this->upload->data());
}
}
This code working fine through xampp. But I'm facing error in live server/cpanl. When I try to upload video every time it shows following error,
array(1) {
["error"]=> string(43)
"You did not select a file to upload." }
Looks like uploads or functions might be disabled inside php.ini
trying running your code with error_reporting(E_ALL); to see if some
error occured except for You did not select a file to upload. error
Usually we can get the form data in Codeigniter by using $this->input->get('field_name') or $this->input->post('field_name') and that's fine.
In raw PHP we use $_FILES["fileToUpload"]["name"] to get the file name that the user trying to upload.
My question is: Is there any Codeigniter way to get the name of the file that needs to be uploaded?
I am trying to say that i need to get the file name that the user is trying to upload before trying to save it in my server using Codeigniter library instead of using raw PHP global $_FILES variable.
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
// get the user submitted file name here
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
Here is the 2 version doc is for 2 and for 3
if you want to get the file name in backend:
$this->upload->file_name It will work based on system/library/upload.php
this function.
public function data()
{
return array (
'file_name' => $this->file_name,
'file_type' => $this->file_type,
...
);
}
If you need to get file name...
Before saving to server... you have work in javascript
<?php echo "<input type='file' name='userfile' size='20' onchange='changeEventHandler(event);' />"; ?>
onchange event in javascript:
<script>
function changeEventHandler(event){
alert(event.target.value);
}
</script>
$data = array('upload_data' => $this->upload->data());
// use file_name within the data() the final code will be
$data = array('upload_data' => $this->upload->data('file_name'));
CodeIgniter Unable to load the requested file: upload_form.php
I am getting this type of An Error Was Encountered.
Here is my controller file that i am uploading.
Controller
Upload.php
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
Here i am uploading my view file.
View
Upload_form.php
<?php echo $error; ?>
<?php echo form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" size="20">
<input type="submit" value="upload">
<?php echo form_close(); ?>
I just Googled Example for multi user role having Admin, user by using CodeIgniter and I got a good result set.
Then I noticed the below link which I got from the google result which is what you need.
http://www.w3programmers.com/making-multi-level-login-system-codeigniter/
Note: Please spend time on researching before posting to SO!!!!
Step-1
User Table
ID | Name | Email | Password | Role
==============================================
1 | abc | abc#c.c | ASDFAS | user
2 | def | def#c.c | adfasdfsa | admin
Step-2
Login Controller
public function index()
{
if($this->isLoggedin()){ redirect(base_url().'login/dashboard');}
$data['title']='Login Boiler Plate';
if($_POST)
{
$config=array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false) {
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$data['csrf'] = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
$data['title']='Login Boiler Plate';
$this->load->view('login',$data);
} else {
// if validation passes, check for user credentials from database
$data = $this->security->xss_clean($_POST);
$user = $this->Login_model->checkUser($data);
if ($user) {
// if an record of user is returned from model, save it in session and send user to dashboard
$this->session->set_userdata($user);
redirect(base_url() . $user['role']);
} else {
// if nothing returns from model , show an error
$data['errors'] = 'Sorry! The credentials you have provided are not correct';
$data['csrf'] = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
$data['title']='Login Boiler Plate';
$this->load->view('login',$data);
}
}
}
else
{
$data['csrf'] = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
$this->load->view('login',$data);
}
}
To see Model and forms start up Read Codeigniter 3.x Login with Form Validation -Boiler plate
Maintain one table for admin users with roles.according to roles you can fetch and display data or redirect to different pages as per your need.
Thank you.
Rename "Upload_form.php" to "upload_form.php"
I'm trying to upload image files using codeigniter 3 but it's not working. No matter what I do, it always says "You didn't select a file to upload". It logs an error on the console saying error 500 when i click on the error in the Network tab then it redirects me to a new tab where it says that error.
Here is my HTML Code:
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<form method="post" enctype="multipart/form-data" action="<?php echo base_url('index.php/welcome/upload'); ?>">
<input type="text" name="username" value="Zahid Saeed">
<input type="file" name="profile_img">
<button type="submit">Submit Form</button>
</form>
</div>
and here is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper("url");
}
public function index()
{
$this->load->view('welcome_message');
}
public function upload() {
$config = array(
"upload_path" => "./uploads/",
"allowed_types" => "gif|jpg|png"
);
echo "<pre>";
print_r($this->input->post());
print_r($_FILES);
echo "</pre>";
$this->load->library("upload", $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload("profile_img")) {
echo $this->upload->display_errors();
echo "IN IF";
}
else {
echo "img uploaded successfully";
}
}
}
One more thing, the exact code is working on the linux machine and in fact on the server. But it's not working on my laptop. I'm using Windows 8.1
Thanks in Advance
may be its php.ini problem
Open your php.ini file
search for extension=php_fileinfo.dll
if you are using xampp it may be commented by default
change
;extension=php_fileinfo.dll
to
extension=php_fileinfo.dll
and restart your xampp...
this was solve my problem
Might be a good idea to use absolute paths for your upload path
$this->upload_config['upload_path'] = FCPATH . 'uploads/';
When I run your code, it works under WAMP64 on Windows 10 Home, ie the file is uploaded and I get to see
Array
(
[username] => Zahid Saeed
)
Array
(
[profile_img] => Array
(
[name] => header-background.png
[type] => image/png
[tmp_name] => C:\wamp64\tmp\php34DA.tmp
[error] => 0
[size] => 563
)
)
img uploaded successfully
This code not supporting obj and fbx formats for file uploading what i do change for this
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper("url");
}
public function index()
{
$this->load->view('welcome_message');
}
public function upload() {
$config = array(
"upload_path" => "./uploads/",
"allowed_types" => "gif|jpg|png"
);
echo "<pre>";
print_r($this->input->post());
print_r($_FILES);
echo "</pre>";
$this->load->library("upload", $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload("profile_img")) {
echo $this->upload->display_errors();
echo "IN IF";
}
else {
echo "img uploaded successfully";
}
}
}
//check here if file is not empty
if(!empty($_FILES['attach_file']['name'])){
$config['upload_path'] = APPPATH.'../assets/images/'; $config['allowed_types'] = 'jpg|jpeg|png|mp4'; $config['file_name'] = 'attach_file_'.time(); $config['max_size'] = "1024";$config['max_height']= "800";$config['max_width'] = "1280";$config['overwrite'] = false;$this->upload->initialize($config);if(!($this->upload->do_upload("attach_file"))){$data['error']['attach_file'] = $this->upload->display_errors();else{ $coverPhotoData = $this->upload->data(); $coverPhoto =$coverPhotoData['file_name'];}}elseif($this->input->get('cup')){$coverPhoto = $previous['attach_file'];}
the view, as an action after choosing and submitting the file it calls the csv/importcsv.
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" ><br><br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>
this is where i think the error happens, and i have tried changing the path of the file time and time again but still does not work, sorry new to ci, i'm just following some tutorial sites and trying to understand their codes.
the model
`
class Csv_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_sampledb() {
$query = $this->db->get('sampledb');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
function insert_csv($data) {
$this->db->insert('sampledb', $data);
}
}
?>`
the controller
`
class Csv extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('csv_model');
$this->load->library('csvimport');
}
function index() {
$data['sampledb'] = $this->csv_model->get_sampledb();
$this->load->view('csvindex', $data);
}
function importcsv() {
$data['sampledb'] = $this->csv_model->get_sampledb();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'first_name'=>$row['first_name'],
'last_name'=>$row['last_name'],
'item_name'=>$row['item_name'],
'item_price'=>$row['item_price'],
'item_quantity'=>$row['item_quantity'],
'email_ad'=>$row['email_ad'],
'phone_num'=>$row['phone_num'],
'shipping_cost'=>$row['cost'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
/END OF FILE/
?>`
as for the library i downloaded something from github, i copied and pasted it at application/libraries/csv/csvimport.php as said in the tutorial, i dont know whats happening. my main concern is in the view file, its returning a page not found after uploading,is my path wrong?when looking at firebug it can parse the data of the csv file but cannot save it due to the page not found, is my path wrong?thanks