I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('user');
}
function add(){
if($this->input->post('userSubmit')){
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
//Prepare array of user data
$userData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'picture' => $picture
);
//Pass user data to model
$insertUserData = $this->user->insert($userData);
//Storing insertion status message.
if($insertUserData){
$this->session->set_flashdata('success_msg', 'User data have been added successfully.');
}else{
$this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
}
}
//Form for adding user data
$data['data']=$this->user->getdata();
$this->load->view('show',$data);
}
public function show()
{
#code
$data['data']=$this->user->getdata();
$this->load->view('show',$data);
}
}
I have this in my model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Model{
function __construct() {
$this->load->database();
$this->tableName = 'users';
$this->primaryKey = 'id';
}
public function insert($data = array()){
if(!array_key_exists("created",$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified",$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
$insert = $this->db->insert($this->tableName,$data);
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
public function getdata()
{
$query=$this->db->get('users');
return $query->result_array();
}
}
Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:
root folder->image:
-application
-system
-uploads
.images(images are saved here)
Now in the problem is with view. I am trying to access the stored images dynamically like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>show</title>
</head>
<body>
<table border='1' cellpadding='4'>
<tr>
<td><strong>User_Id</strong></td>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
<td><strong>Option</strong></td>
</tr>
<?php foreach ($data as $p): ?>
<tr>
<td><?php echo $p['id']; ?></td>
<td><?php echo $p['name']; ?></td>
<td><img src="../uploads/images/<?php echo $p['picture']; ?>" /> </td>
<td>
View |
</td>
</tr>
<?php endforeach; ?>
</table>
With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:
<img src="../uploads/images/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
or like this
<img src="../../uploadsimages/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.
try this
<img src="<?php echo base_url('uploads/images/'.$p['picture']); ?>"/>
insted of this line
<img src="../uploads/images/<?php echo $p['picture']; ?>" />
also set your folder location corectly
Just a silly mistake. I made my virtual host to point up to index.html of root folder. so just pointing up to root folder the problem was solved.
Related
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/');
}
}
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'];}
I am relatively new to CodeIgniter but I can grasp a thing or two.
I am currenly facing a problem where I want the admin to view or download uploaded files (pdf and doc) submitted upon user registration.
Everything is working well but I would wish the admin to download the files not just see the filename.
Here is my Controller:
<?php
class NominationController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Nomination');
$this->load->library('session');
}
/*
function for manage Nomination.
return all Nominations.
created by your name
created at 25-07-16.
*/
public function manageNomination() {
$data["Nominations"] = $this->Nomination->getAll();
$this->load->view('Nomination/manage-Nomination', $data);
}
/*
function for add Nomination get
created by your name
created at 25-07-16.
*/
public function addNomination() {
$this->load->view('Nomination/add-Nomination');
}
/*
function for add Nomination post
created by your name
created at 25-07-16.
*/
public function addNominationPost() {
$data['title'] = $this->input->post('title');
$data['first_name'] = $this->input->post('first_name');
$data['last_name'] = $this->input->post('last_name');
$data['email_id'] = $this->input->post('email_id');
$data['phone_no'] = $this->input->post('phone_no');
$data['company'] = $this->input->post('company');
$data['popularity'] = $this->input->post('popularity');
$data['nominee_type'] = $this->input->post('nominee_type');
$data['innovation_name'] = $this->input->post('innovation_name');
$data['organisation_type'] = $this->input->post('organisation_type');
$data['category'] = $this->input->post('category');
$data['date_of_innovation'] = $this->input->post('date_of_innovation');
$data['company_offices'] = $this->input->post('company_offices');
$data['need_addressed'] = $this->input->post('need_addressed');
$data['user_benefits'] = $this->input->post('user_benefits');
$data['uniqueness'] = $this->input->post('uniqueness');
if ($_FILES['supporting_documents']['name']) {
$data['supporting_documents'] = $this->doUpload('supporting_documents');
}
$this->Nomination->insert($data);
$this->session->set_flashdata('success', 'Nomination added Successfully');
redirect('success');
}
/*
function for edit Nomination get
returns Nomination by id.
created by your name
created at 25-07-16.
*/
public function editNomination($Nomination_id) {
$data['Nomination_id'] = $Nomination_id;
$data['Nomination'] = $this->Nomination->getDataById($Nomination_id);
$this->load->view('Nomination/edit-Nomination', $data);
}
/*
function for edit Nomination post
created by your name
created at 25-07-16.
*/
public function editNominationPost() {
$Nomination_id = $this->input->post('Nomination_id');
$Nomination = $this->Nomination->getDataById($Nomination_id);
$data['title'] = $this->input->post('title');
$data['first_name'] = $this->input->post('first_name');
$data['last_name'] = $this->input->post('last_name');
$data['email_id'] = $this->input->post('email_id');
$data['phone_no'] = $this->input->post('phone_no');
$data['company'] = $this->input->post('company');
$data['popularity'] = $this->input->post('popularity');
$data['nominee_type'] = $this->input->post('nominee_type');
$data['innovation_name'] = $this->input->post('innovation_name');
$data['organisation_type'] = $this->input->post('organisation_type');
$data['category'] = $this->input->post('category');
$data['date_of_innovation'] = $this->input->post('date_of_innovation');
$data['company_offices'] = $this->input->post('company_offices');
$data['need_addressed'] = $this->input->post('need_addressed');
$data['user_benefits'] = $this->input->post('user_benefits');
$data['uniqueness'] = $this->input->post('uniqueness');
if ($_FILES['supporting_documents']['name']) {
$data['supporting_documents'] = $this->doUpload('supporting_documents');
unlink('./uploads/Nomination/'.$Nomination[0]->supporting_documents);
}
$edit = $this->Nomination->update($Nomination_id,$data);
if ($edit) {
$this->session->set_flashdata('success', 'Nomination Updated');
redirect('success');
}
}
/*
function for view Nomination get
created by your name
created at 25-07-16.
*/
public function viewNomination($Nomination_id) {
$data['Nomination_id'] = $Nomination_id;
$data['Nomination'] = $this->Nomination->getDataById($Nomination_id);
$this->load->view('Nomination/view-Nomination', $data);
}
/*
function for delete Nomination created by your name
created at 25-07-16.
*/
public function deleteNomination($Nomination_id) {
$delete = $this->Nomination->delete($Nomination_id);
$this->session->set_flashdata('success', 'Nomination deleted');
redirect('manage-Nomination');
}
/*
function for activation and deactivation of Nomination.
created by your name
created at 25-07-16.
*/
public function changeStatusNomination($Nomination_id) {
$edit = $this->Nomination->changeStatus($Nomination_id);
$this->session->set_flashdata('success', 'Nomination '.$edit.' Successfully');
redirect('manage-Nomination');
}
/*
function for upload files
return uploaded file name.
created by your name
created at 25-07-16.
*/
public function doUpload($file) {
$config['upload_path'] = './uploads/Nomination';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($file))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data['upload_data']['file_name'];
}
}
}
Here is my View.php
<tr>
<td width='30%' class='label-view text-right'>
<?php echo SiteHelpers::activeLang('Uniqueness', (isset($fields['uniqueness']['language'])? $fields['uniqueness']['language'] : array())) ;?>
</td>
<td><?php echo $row['uniqueness'] ;?> </td>
</tr>
<tr>
<td width='30%' class='label-view text-right'>
<?php echo SiteHelpers::activeLang('Supporting Documents', (isset($fields['supporting_documents']['language'])? $fields['supporting_documents']['language'] : array())) ;?>
</td>
<td><?php echo $row['supporting_documents'] ;?></td>
</tr>
Here is the screenshot of my output:
I would like the pdf file or doc to be clickable
Here is how I have set my MySQL:
..just in case its not set correctly
I feel its something small but my eyeballs are sore for the past week and I think Google knows my name and where I sleep by now :)
Any help accorded will go a long away.
Thank you
According to the documentation:
https://www.codeigniter.com/user_guide/helpers/url_helper.html#base_url
You can import the Url Helper like this:
$this->load->helper('url');
Then, you can use
Download
The method base_url will return your site base URL, as specified in your config file. Plus, the argument will concatenate that URL with the string you supplied. That will be the complete URL of your 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
I am using Yii framework and I want to create user registration page. Everything seems to work fine but when i want to upload user image, I get an error message:
include(Self.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory
Here is my SiteController code:
public function actionRegister()
{
$model=new RegisterForm;
// uncomment the following code to enable ajax-based validation
if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate())
{
$user = new User;
$user->username = $_POST['RegisterForm']['username'];
$password = $_POST['RegisterForm']['password'];
$salt = Security::GenerateSalt(128);
$user->password = hash('sha512', $password.$salt);
$user->question = $_POST['RegisterForm']['question'];
$user->answer = $_POST['RegisterForm']['answer'];
$user->salt = $salt;
$user->email = $_POST['RegisterForm']['email'];
$user->fullname = $_POST['RegisterForm']['fullname'];
$user->birth = $_POST['RegisterForm']['birth'];
$user->avatar = CUploadedFile::getInstance($model,'image');
$user->avatar->saveAs('/images/users.test.jpg');
$user->about = $_POST['RegisterForm']['about'];
$user->signup = date('d/m/y');
$user->login = date('d/m/y');
$user->save();
}
}
$this->render('register',array('model'=>$model));
}
Here is my RegisterForm model code:
<?php
class RegisterForm extends CFormModel
{
[.....]
public $avatar;
[.....]
public function rules()
{
return array(
[......]
array('avatar', 'file',
'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 2,
'tooLarge'=>'The file was larger than 2MB. Please upload a smaller file.',
'wrongType'=>'Please upload only images in the format jpg, gif, png',
'tooMany'=>'You can upload only 1 avatar',
'on'=>'upload'),
[......]
}
The view:
<div class="row">
<?php echo $form->labelEx($model,'avatar'); ?>
<?php echo CHtml::activeFileField($model, 'avatar'); ?>
<?php echo $form->error($model,'avatar'); ?>
</div>
Might be a directory permission problem. To be sure if it is, do a
chmod 0777 <dir_name>
Once you are sure, you can reset the permissions properly.