Cannot use custom library in CodeIgniter 3 - php

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...

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

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

codeigniter admin panel automatic page creation

I want to create one controller file which is creating automatically a function if i create a menu dynamically and also want to create view page which is connencted to this main controller.. how to do that?
Current code:
public function our_history()
{
$data['category']= $this->menu_model->getCategory('$lang');
$data['subcategory']= $this->menu_model->getSubCategory('$lang');
$this->load->view('vwMain',$data);//Left Menu }
}
Follow below steps Hope that makes sense.
-- Admin section --
/*content.php -- controller starts here */
class Content extends VCI_Controller {
# Class constructor
function __construct()
{
parent::__construct();
$this->load->model('content_model');
}
/*
Add page logic
*/
function edit_page($id = null)
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
//Set the view caption
$view_data['caption'] = "Edit Content";
//Set the validation rules for server side validation
// rule name editcontent should be defined
if($this->form_validation->run('editcontent')) {
//Everything is ok lets update the page data
if($this->content_model->update(trim($id))) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
/*
Edit page logic
*/
function add_page()
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
$view_data['caption'] = "Edit Content";
if($this->form_validation->run('editcontent')) {
// after passing validation rule data to be saved
// editcontent rule must be defined in formvalidations file
//Everything is ok lets update the page data
if($this->content_model->add()) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
}
/**
* content.php -- controller ends here
*/
/*
Content_model starts here
*/
class Content_model extends CI_Model {
// update logic goes here
function update($id = null) {
if(is_null($id)) {
return false;
}
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->update('content', $data);
return true;
}
// Add logic goes here
function add() {
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->insert('content', $data);
return true ;
}
}
/*
Content_model ends here # Admin section changes ends here
*/
-- Add view files also to admin section content_editpage.php
Now go to your routes.php file for front section --
add below line at last --
$route['(:any)'] = 'page/view_usingslug/$1';
This will be for all urls like --- http://yourdomainname/your_slug_name
// create again a controller in front section page.php --
class page extends VCI_Controller {
function __construct()
{
parent::__construct();
}
function view_usingslug($slug='')
{
// retrieve the data by slug from content table using any model class and assign result to $view_dat
$this->_vci_view('page',$view_data);
//page.php will be your view file
}
}
Suppose Your URL is
www.example.com/controllername/methodname/menutitle1
or
www.example.com/controllername/methodname/menutitle2
So this is how you handle these pages.
public function method()
{
$menutitle = $this->uri->segment(3);
$query = $this->db->get_where('TableName',array('Menutitle'=>$menutitle))
$data['content'] = $query->row()->page_content;
$this->load->view('common_page',$data);
}

I need to enter an array of data in my database, the data is imported from a excel file

I am using Excel Reader to import a excel file into my database. I am also using postgres and cakephp. Now I have problem for import the imformation to my DataBase, I'm trying to enter through a for.
message of error:
Call to a member function create() on a non-object.
my controller.
<?php
App::import('Vendor', 'excel_reader2');
class SoyaproductorcomprasController extends AppController {
public $components = array('Session','RequestHandler');
public function logout() {
$this->redirect($this->Auth->logout());
}
public function excel() {
$this->loadModel('SoyaProductorCompra');
if ($this->request->is('post')) {
$datos = new Spreadsheet_Excel_Reader();
$datos->read($this->request->data['SoyaProductorCompra']['excel']['tmp_name']);
for ($i = 1; $i <= $datos->sheets[0]['numRows']; $i++) {
$this->SoyaProductorCompra->create();
$this->request->data['SoyaProductorCompra']['user_id'] = $this->Auth->user('id');
$this->request->data['SoyaProductorCompra']['campana'] = $datos->sheets[0]['cells'][$i][1];
$this->request->data['SoyaProductorCompra']['nit'] = $datos->sheets[0]['cells'][$i][2];
$this->request->data['SoyaProductorCompra']['proveedor'] = $datos->sheets[0]['cells'][$i][3];
$this->request->data['SoyaProductorCompra']['regimengrano'] = $datos->sheets[0]['cells'][$i][4];
$this->request->data['SoyaProductorCompra']['codigograno'] = $datos->sheets[0]['cells'][$i][5];
$this->request->data['SoyaProductorCompra']['producto'] = $datos->sheets[0]['cells'][$i][6];
$this->request->data['SoyaProductorCompra']['toneladas'] =$datos->sheets[0]['cells'][$i][7];
$this->request->data['SoyaProductorCompra']['preciodolar'] = $datos->sheets[0]['cells'][$i][8];
$this->request->data['SoyaProductorCompra']['total'] = $datos->sheets[0]['cells'][$i][9];
$this->request->data['SoyaProductorCompra']['fecharegistro'] = $datos->sheets[0]['cells'][$i][10];
$this->SoyaProductorCompra->save($this->data);
}
}
}
}
?>
my view.
<?php echo $this->Form->create('SoyaProductorCompra', array('enctype' => 'multipart/form-data'));?>
<?php
echo $this->Form->input('excel',array( 'type' => 'file', 'label'=>'Ingrese excel'));
echo $this->Form->end('Submit')
?>
Not sure, try calling $this->SoyaProductorCompra->create(); just before $this->SoyaProductorCompra->save($this->request->data);

Refactoring Controller to Model in Code Igniter

It's come to my attention that my image processing code that I currently have in my controller would be better suited in a model, but I'm not sure even where to start to do this.
I have a controller that handles uploading an image, renaming the file and storing it in the database using Doctrine:
<?php
class Addimage extends Controller
{
function index()
{
$vars['content_view'] = 'uploadimage';
$this->load->view('template', $vars);
}
public function do_upload()
{
$this->load->library('form_validation');
if($this->_submit_validate() == FALSE)
{
/*THIS CODE BLOCK IS DUPLICATED FROM MY HOME PAGE CONTROLLER - this is one of the reasons I want to refactor.*/
$vars['recentimages'] = Doctrine_Query::create()
->select('photo_path')
->from('Gif g')
->orderBy('g.created_at DESC')
->limit(12)
->execute();
$vars['title'] = 'Home';
$vars['content_view'] = 'welcome_message';
$this->load->view('template_front', $vars);
}
else
{
$basedir = $this->config->item('server_root') . $this->config->item('upload_dir');
//If the directory doesn't already exist, create it.
if (!is_dir($basedir))
{
mkdir($basedir, 0777);
}
$config = array(
'allowed_types' => "gif",
'upload_path' => $basedir,
'remove_spaces' => true
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$data['error'] = 'There was a problem with the upload';
}
else
{
$image_data = $this->upload->data();
$fileName = $image_data['file_name'];
$title = $this->input->post('title');
//Rename File based on how many of that letter
//are already in the database
$imageCount = Doctrine_Query::create()
->select('COUNT(i.id) as num_images')
->from('Gif i')
->execute();
$imageCount = $imageCount[0]->num_images++;
//Rename file based on title and number of images in db.
$newFileName = preg_replace('/[^a-zA-Z0-9\s]/', '', $title) . '_' . $imageCount . $image_data['file_ext'];
rename($basedir . $fileName, $basedir . $newFileName);
$gif = new Gif();
$gif->photo_path = $newFileName;
$gif->title = $title;
if(Current_User::user())
{
$gif->User = Current_User::user();
}
else
{
$gif->User = Doctrine::getTable('User')->findOneById($this->config->item('anonuid'));
}
$gif->save();
}
redirect('/', 'location');
}
}
private function _submit_validate()
{
$this->form_validation->set_rules('title', 'Title', 'required');
return $this->form_validation->run();
}
}
I would like to be able to have most of this in a model, because I'm using a template system for the views where my uploadimage.php view is just the upload form so that it can be dropped on any page. Also, I only have experience using Doctrine models.
Thanks for any help in advance
I had a very similar issue on my own project: duplication in the controllers. I think in your case it makes sense to only move parts of that logic into the model, because most of it actually makes sense to be in a controller.
Rendering view definitely should be in a controller, and input validation as well. I would move the transactional part to the model: the SQL, file handling and image manipulation.
You will then still have some duplication but I see no other way since controller logic and model logic are so interwoven in this case.

Categories