codeigniter upload Excel and display content on view - php

I'm using codeigniter and phpspreadsheet to import the Excel file data. Now, in my code can read the Excel contents as well but I got error when trying to transfer DATA and display it on views. Please help to adv.
1. Error code.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: sheetData
Filename: views/upload_view.php
Line Number: 18
3. Controller code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//Load plugin
require (APPPATH .'third_party\vendor\autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view');
}
function do_upload()
{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'xls|xlsx';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('upload_file')){
$error = array('error' => $this->upload->display_errors());
var_dump ($error);
}
else{
$data = array('upload_data' => $this->upload->data());
$full_path = $data['upload_data']['full_path'];
//---------Config read file content----------//
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); //Excel 2007 or higher
//$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); //Excel 2003
$spreadsheet = $reader->load($full_path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
//var_dump('<pre>');
//var_dump($sheetData);
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view', $sheetData);
}
}
}
/* End of file Upload.php */
/* Location: ./application/controllers/Upload.php */
2. View code
<?php
foreach ($sheetData as $value) {
echo $value -> A;
}
?>

Try this way:
$dataarr = array();
$dataarr['sheetData'] = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view', $dataarr);
I think it will help you.

Related

Pass the value from a Controller to the view

I created a form and passed the values for name and picture from the form. The value is accessed from the Upload controller as follows:
$data = array(
'title' => $this->input->post('title', true),
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
return $data;
I need to pass these values to the view so, I modified the above code as:
class Upload extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function input_values(){
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data); }
function add(){
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
//logo image upload
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
}
But I am able to get only the value of title. Following error occurs for both name and title:
Message: Undefined variable: name
I have accessed the variables from the view as follows:
<?php var_dump($title)?>
<?php var_dump($name)?
<?php var_dump($picture)?>
so, this part is where you get the post data and load view (contain the upload form)
public function input_values() {
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data);
}
then this part is handle the post request from the upload form:
function add() {
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
and this part is where you upload the file
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
when you call add() function, it call input_values() function then load views then the next line of codes won't be executed (cmiiw).
so, maybe you want to change with this :
public function index() {
if ($this->input->post()) {
// then handle the post data and files tobe upload here
// save the post data to $data, so you will able to display them in view
} else {
// set the default data for the form
// or just an empty array()
$data = array();
}
// if the request was not a post, render view that contain form to upload file
$this->load->view('nameOfTheView', $data);
}

Cannot use custom library in CodeIgniter 3

I want to use https://www.verot.net/php_class_upload_download.htm library in my project for resizing images. However, when I submit form it gives this error
I have loaded the library in the autoloader and I renamed library to "my_upload" and gave the same class name.
However, I do not know why this error occurs.
And here is my controller:
<?php
class Blog extends CI_Controller{
function __construct() {
parent::__construct();
}
public function add() {
if(!$this->session->userdata('logged_in')) {
$this->session->set_flashdata('not_loggedin','<div class="alert alert-success text-center">Please Login</div>');
redirect('login');
}
$data['title'] = 'Ədd nyus';
$data['author'] = $this->Blog_model->get_author();
$data['category'] = $this->Blog_model->get_category();
$this->load->view('templates/header');
$this->load->view('blog/add', $data);
$this->load->view('templates/footer');
}
public function create() {
if(!$this->session->userdata('logged_in')) {
$this->session->set_flashdata('not_loggedin','<div class="alert alert-success text-center">Please Login</div>');
redirect('login');
}
//insert image
$now = date("YmdHis");
$this->my_upload->upload($_FILES["userfile"]);
if ( $this->my_upload->uploaded == true ) {
$this->my_upload->allowed = array('jpg|png');
$this->my_upload->file_new_name_body = 'image_resized' . $now;
$this->my_upload->image_resize = true;
$this->my_upload->image_ratio_fill = true;
$this->my_upload->image_x = 360;
$this->my_upload->image_y = 236;
// $this->my_upload->image_ratio_y = true;
$this->my_upload->process('C:\xampp\htdocs\edu-center\assets\img\blog');
if ( $this->my_upload->processed == true ) {
$this->my_upload->clean();
$post_image = $_FILES["userfile"]["name"];
}
} else {
$post_image = '';
}
//insert the user registration details into database
$randnum = mt_rand(100000,999999);
$slugtitle = mb_strtolower($this->input->post('title_az'), 'UTF-8') . '-' .$randnum;
$slug = url_title($slugtitle);
$post_image = str_replace(' ', '_', $post_image);
$post_image = preg_replace('/_+/', '_', $post_image);
date_default_timezone_set('Asia/Baku');
$data = array(
'title_az' => strip_tags($this->input->post('title_az')),
'title_rus' => strip_tags($this->input->post('title_rus')),
'author_id' => $this->input->post('author_id'),
'category_id' => strip_tags($this->input->post('category')),
'body_az' => $this->input->post('body_az'),
'body_rus' => $this->input->post('body_rus'),
'date' => date("d-m-Y"),
'news_slug' => $slug,
'img' => $post_image
);
$this->Blog_model->add_news($data);
$this->session->set_flashdata('changed_msg','<div class="alert alert-success text-center">Ваши изменения были сохранены!</div>');
redirect('blog');
}
Where can be the problem?
imho the best way is to create a third party library for that
copy your class into your folder application/third_party/upload/
and in your controller you simply inlcude this file like:
require_once(APPPATH."third_party/upload/my_upload.php");
$objUpload = new my_upload($_FILES);
If you really want a library for that try the following:
The problem is your library gets instantiated by CI - you don't really have control over the constructor
the only way you could do is to include a "wrapper" library
e.g.
<?php
require_once(APPPATH."libraries/my_upload.php");
class Uploadwrapper_library
{
public function get($files)
{
return new my_upload($files);
}
}
in your controller you could do
$this->load->library("uploadwrapper_library");
$objMyUpload = $this->uploadwrapper_library->get($_FILES);
Well if you look at the file - system/libraries/Upload.php it's constructor requires a parameter...
public function __construct($config = array())
So with your MY_Upload class which is CI's way to allow you to override core classes, you need to follow suit with the class you are extending.
You've not shown your constructor so I don't know what you have attempted with your constructor...

Codeigniter upload file name

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'));

ci csv file upload to database but page not found

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

Cakephp2.0 missing component

I used a component name upload.php and save it in /app/controllers/components/ directory.
After that I used code in my controller like
<?php
App::uses('AppController', 'Controller');
App::uses('BarcodeHelper','Vendor');
/**
* OesUsers Controller
*
* #property OesUser $OesUser
*/
class OesUsersController extends AppController {
var $name = 'Images';
var $helpers = array('Html', 'Form');
var $components = array('upload');
function upload() {
if (empty($this->data)) {
$this->render();
} else {
$this->cleanUpFields();
// set the upload destination folder
$destination = realpath('../../app/webroot/img/uploads/') . '/';
// grab the file
$file = $this->data['Image']['filedata'];
// upload the image using the upload component
$result = $this->Upload->upload($file, $destination, null, array('type' => 'resizecrop', 'size' => array('400', '300'), 'output' => 'jpg'));
if (!$result){
$this->data['Image']['filedata'] = $this->Upload->result;
} else {
// display error
$errors = $this->Upload->errors;
// piece together errors
if(is_array($errors)){ $errors = implode("<br />",$errors); }
$this->Session->setFlash($errors);
$this->redirect('/images/upload');
exit();
}
if ($this->Image->save($this->data)) {
$this->Session->setFlash('Image has been added.');
$this->redirect('/images/index');
} else {
$this->Session->setFlash('Please correct errors below.');
unlink($destination.$this->Upload->result);
}
}
}
After save that I find error that is missing component. I could not find any mistake.Can any body help me?
You have placed the component in the wrong folder. In CakePHP 2.x, components are placed in app/Controller/Component. You also have to rename the component from upload.php to UploadComponent (and probably adapt the code to make it work with CakePHP 2.x).

Categories