Hi i want to store multiple file path in database, but the following code is storing just one file path
Kindly some one help.
My Controller
<?php
class upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view("header.php");
$this->load->view('main_views', array('error' => ' ' ));
$this->load->view("footer.php");
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
// no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
$this->load->view("header.php");
$this->load->view('main_views', $error);
$this->load->view("footer.php");
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->model('post_model');
$this->post_model->main_model();
$this->load->view("header.php");
$this->load->view('main_views');
$this->load->view("footer.php");
}
}
?>
My Model
<?php
class post_model extends CI_Model
{
function main_model()
{
$filepath = $this->upload->data()['file_name'];
$this->db->trans_begin();
$this->db->query("insert into post (post_pic)
values ('$filepath')");
$ad_id = $this->db->insert_id();
}
}
?>
Views
<span id="filediv"><input name="userfile" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile2" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile3" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile2" type="file" id="file"/></span><br/>
extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it
Views
- input name change to name="userfile[]"
You can use multiple upload of codeignter
https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Thanks
You have to upload each $_FILES
foreach ( $_FILES as $key => $value ) {
if (! empty ( $value ['name'] )) {
//change the file name
$config ['file_name'] = date('Y_m_d') . '_' . $value ['name'];
$this->upload->initialize($config);
if (! $this->upload->do_upload ( $key )) {
// handle error function
$this->handle_error ( $this->upload->display_errors () );
} else {
$files [$i] = $this->upload->data ();
++ $i;
}
}
}
Here in $files array you will get the details of the uploaded files which can be used further for model to insert into database the path of the files.
Related
I have followed all the answers available on internet related to this topic, after 4 hours of searching and trying still no success..😣
Error thrown is
You did not select a file to upload.
EDIT
Tried using $_FILES method too.
I tried if($this->input->post('userfile')!==null)
to check whether image is being passed to controller or not and it turns out it doesn't as the if condition was not executed.
I have followed this guide to upload files on server.
https://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload
don't know what the issue is.
you can find the code in the above link.
my .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
EDIT:
I tried all the suggestions you guys provided.
Yeah it was my mistake to check the image via $_POST instead of $_FILES
But still the issue is same. I am posting the code I use and the URL which you can check too.
Any help would really be appreciated thankyou.
ImageUploadController.php
<?php
class ImageUploadController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('image-upload/upload_form', array('error' => ' ' ));
}
public function store($workType)
{
$config['upload_path'] = './assets/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('imageFile'))
{
if(isset($_FILES['imageFile']))
echo "isset";
$error = array('error' => $this->upload->display_errors());
$this->load->view('image-upload/upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('image-upload/upload_success', $data);
}
}
}
?>
upload_form.php
https://gist.github.com/VickySalunkhe/1dc66ec6d3af8cf097a5c01b5009c804
upload_result.php
https://gist.github.com/VickySalunkhe/691626e4fe6dd8a8b3896d210e4b22b9
Route set for the request
$route['upload'] = 'ImageUploadController';
//stores the images on server
$route['store/(:any)'] = 'ImageUploadController/store/$1';
you can ignore the part for second route , its for some other logic part which will be implemented later on.
To upload a file in CodeIgniter 3 I recommend you use the File Uploading class.
You will find the link here: Uploading files in CodeIgniter
For what I see, is what you used above.
The documentation says you have to first load the upload library, with some configuration settings (see docs):
$this->load->library('upload', $config)
And then the method that does the actual upload (based on config params) is this:
$this->upload->do_upload('<your-file-name>');
Notice where it says, there you have to use the name of the file you are uploading via HTML. The file itself is not found on a POST array, but in the FILES array, everytime you are uploading a file using the HTML <input type="file"> element.
Try Blow Code
1) HTML:
<form action="/profile_upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
2) PHP file:
if($_FILES['file']['name']!='') {
$config['upload_path'] = './uploads/admin/big';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '10240';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
// ERROR
$error = array('error' => $this->upload->display_errors());
}
else {
// SUCCESS
$file_name = $this->upload->file_name;
}
}
Check form enctype attribute e.g
check $_FILES variable empty or not.
View:
<?php echo form_open_multipart('updateFunctionName');?>
<div class="col-md-6">
<div class="form-group">
<label for="artworkpath">Artwork</label>
<input type="file" class="form-control" id="artworkpath" name="artworkpath" value="<?php echo $artworkpath; ?>">
</div>
</div>
</form>
Controller:
function updateFunctionName(){
$artworkpath = $this->input->post('artworkpath');
$CheckFileName = true;
if ($_FILES['artworkpath']['size'] == 0 && $_FILES['artworkpath']['error'] == 0)
{
$CheckFileName = false;
}
else
{
$filename2 = 'Artwork_'.rand(0,999999);
if( ! is_dir('uploads') ){mkdir('uploads',0777,TRUE); };
$path='uploads/';
$imgtmpname=$_FILES['artworkpath']['tmp_name'];
$name = $_FILES["artworkpath"]["name"];
$ext = end((explode(".", $name)));
$fullpath= $path .$filename2.'.'.$ext;
$filename = $filename2;
move_uploaded_file($imgtmpname,$fullpath);
}
In DB save this variable data in column:
$Info = array();
if ($ext <> '')
{
$Info = array('artworkpath'=>$fullpath, //other fields);
}
else
{
$Info = array(//other fields);
}
$this->user_model->updateRecord($Info, $Id);
}
Model:
function updateRecord($Info, $Id)
{
$this->db->where('Id', $Id);
$this->db->update('tablename', $Info);
}
I have a multipart/form-data with an image upload and some personal data, so I want to include file upload in form validation, I can successfully do this.
However, I now find that there is an issue, ie even if my other form fields have errors and upload file field with no error, then image uploads to folder, how to prevent this, I mean, in my case, If name, email, file fields validation is ok then only file should upload, if name filed validation fails and file field validation ok then file should not upload
here is the code I use:
In Controller:
<?php
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
'profile_img'=>array('field'=>'profile_img', 'label'=>'Design', 'rules'=>'callback__profile_upload')
);
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
function _profile_upload(){
if($_FILES['profile_img']['size'] != 0 && !empty($_FILES['profile_img']) ){
$upload_dir = './profile_pics/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'profile_img_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->upload->initialize($config);
if (!$this->upload->do_upload('profile_img')){
$this->form_validation->set_message('_profile_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('_profile_upload', "No file selected");
return false;
}
}
IN VIEW:
<?php echo form_open_multipart();?>
<?php $name_err = (!empty(form_error('name'))) ? 'err' : ' ';
echo form_input('name',set_value('name'), array('placeholder'=>'Name','class'=>" {$name_err } "));
?>
<?php $email_err = (!empty(form_error('email'))) ? 'err' : ' ';
echo form_input('email',set_value('email'), array('placeholder'=>'EMail','class'=>" {$email_err } "));
?>
<?php
echo form_error('profile_img');
echo form_upload(array('name' =>'profile_img', 'class' => 'inputfile inputfile-4', 'id' => 'profile_img'));
?>
<li><input type="submit" class="special" value="Submit" /></li>
Try once like this.I think for images not need to set rules like other fields.
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
);
And
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
if ($this->_profile_upload()) { //return true if file uploaded successfully otherwise error
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
}
yes that is very obvious that your file get uploads even any other fields' validation failed. You have to initiate image uploading only after form validation success.
For that simply validate file specific requirement in that callback, and do actual uploads after successful form validation.
I have got a solution from codexWorld, I have asked same question over there, and they replied with a tutorial, If anybody still looking for a solution here is the link
http://www.codexworld.com/codeigniter-file-upload-validation/
in the validation call back, we just want to do the file type check
public function _profile_upload($str){
$allowed_mime_type_arr = array('image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('_profile_upload', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('_profile_upload', 'Please choose a file to upload.');
return false;
}
}
and in the main function we just want to do the same as normal, using do_upload and specifying the upload config items, anyhow there will be a second file type check when the function executes, I think that doesn't matter. The code will look like this::
public function profile()
{
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'uploads/files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
/*
*insert file information into the database
*.......
*/
}else{
$data['error_msg'] = $this->upload->display_errors();
}
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
I'm trying to add a file upload function in my website using codeigniter's upload library.
here's my view file (display.php):
<html>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="filename" />
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
</body>
</html>
and here's the controller:
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('filename'))
{
echo 'error!';
}
else
{
echo 'success!';
}
echo 'end upload';
}
$this->load->view('display', $this->data);
}
but the code seems to stop after $this->upload->initialize($config); the file was not uploaded, and there was no message at all. only the 'start upload' message appeared; the echo 'success' , echo 'error' , and echo 'end upload' do not appear.
why is that? can anyone help me??
Late from party, but maybe this can help somebody with same problem. Please try this:
Views:
<?php echo form_open_multipart('test/upload');?>
<input type="file" name="photo">
<?php echo form_close();?>
Controller:
class Test extends CI_Controller {
function upload() {
$config = array(
'upload_path' => './assets/upload/',
'allowed_types'=> 'gif|jpg|png',
'encrypt_name' => TRUE // Optional, you can add more options as need
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('photo')) {
echo '<pre>';
print_r($this->upload->display_errors());
exit();
} else {
echo '<pre>';
print_r($this->upload->data());
exit();
}
}
}
Inside views i recomended use this function form_open_multipart('ctrl/method') but if you prefer using HTML5 forms, just be sure correct the attributes in form like this.
<form action="<?=site_url('ctrl/method')?>" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="photo">
</form>
More preferences in $config['..'] can you find in documentation CodeIgniter https://codeigniter.com/user_guide/libraries/file_uploading.html
Try like this....
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('filename'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('display', $error); //loads the view display.php with error
}
else
{
echo 'success!';
}
echo 'end upload';
$data = array('upload_data' => $this->upload->data());
$this->load->view('display', $data); //loads view display.php with data
}
}
change from
$config['upload_path'] = './assets/img/tempfile/';
to
$config['upload_path'] = 'assets/img/tempfile/';
i check this code this work perfect
simply add this line
$config['allowed_types'] = 'png|gif|jpg|jpeg';
$config['max_size'] = '7000';
after this
$config['upload_path'] = './assets/img/tempfile/';
or you can also set this in view page
action="<?php echo base_url('YourController/testupload');?>"
this is due to php server version and it's option.
1).go to cpanel account
2).click "select php version", in the software section.
3).tap the "fileinfo" chexbox in the php option and save.
now you can upload file perfectly.
Same issue as described. I have fixed it using the following: Open the file system/libraries/Upload.php go to function validate_upload_path() and add the command return TRUE; as a last line inside this function. Save and try again.
use this for image upload:
$valid_extensions = array('jpeg', 'jpg', 'png');
if ($_FILES['filename']['error'] == 0) {
$img = $_FILES['filename']['name'];
$tmp = $_FILES['filename']['tmp_name'];
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
if (in_array($ext, $valid_extensions)) {
$path = "./assets/img/tempfile/" . strtolower($img);
if (move_uploaded_file($tmp, $path)) {
$_POST['filename'] = $path;
}
}
}
use insert query to insert file :
$this->db->insert('table_name', $_POST);
Having the same problem on macOS. It seems that if you are not the "main" user of your laptop/pc, the default permission is "Read Only". You must change it to "Read & Write".
Right click on the folder
Get Info
Sharing and permissions
Change 'Read Only' to 'Read & Write'
add allowed file type parameter in config
$config['allowed_types'] = 'gif|jpg|png';
your code is missing the following,
$this->load->library('upload',$config);
Recorrect it by rewriting the above code.
I'm trying to create update image for user who want to change their photo.The when i click submit on photo upload, there is no photo uploaded and photo's column still no update.
Here is my Contorller:
function foto($id='')
{
$data['data'] = $this->user_model->get_foto($id);
$data['form_action'] = site_url("user/update_foto/$id");
$this->load->view('user/foto_form', $data);
}
function update_foto($id=''){
$this->user_model->update_foto($id);
}
Here is My model:
function get_foto($id=0){
$id = $this->session->userdata('id');
$sql = "SELECT id,foto FROM user WHERE id= '$id'";
$query = $this->db->query($sql);
$data = $query->row_array();
return $data;
}
function update_foto(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto'))
{
$id_user=$this->session->userdata('id');
redirect ("user/foto/$id_user");
} else {
$id_user=$this->session->userdata('id');
$data=array(
'foto'=>$this->input->post('foto')
);
$this->db->where('id',$id_user);
$this->db->update('user',$data);
redirect("user");
}
}
And this is my upload form on view:
<form role="form" action="<?php echo $form_action ?>" class="form-horizontal style-form" method="POST" enctype="multipart/form-data">
<label >Upload Foto</label>
<input type="file" name="foto"/>
<button type="submit">Save</button>
</form>
Any Answer? Many thanks for the answer...
On your controller try replacing this
from
site_url("user/update_foto/$id");
to
site_url("user/update_foto") ./. $id;
Or you could use uri segment refer user guide.
site_url("user/update_foto") ./. $this->uri->segment(4); // unsure id check uri segment in url.
Your route may need to be changed
$route['user/update_foto/(:any)'] = "controllername/foto/$1";
All ways make sure the controller has index()
At your model this is wrong.
$data=array(
'foto'=>$this->input->post('foto')
);
$this->input->post('foto') does not get your file name.
You can try that with this
else {
$id_user=$this->session->userdata('id');
$info=$this->upload->data();
$data=array(
'foto'=>$info['file_name']
);
$this->db->where('id',$id_user);
$this->db->update('user',$data);
redirect("user");
}
better use this line for your upload path
$config['upload_path'] = FCPATH.'upload/';
$file_name = "";
if ($_FILES['foto']['error']!= 4) {
$fileParts = pathinfo($_FILES['foto']['name']);
$file_name = time() . '.' . $fileParts['extension'];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('foto');
}
this is my upload function
public function do_upload()
{
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('customer_photo'))
{
$responce->success = false;
$responce->data['error'] = $this->upload->display_errors();
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->_do_resize($data);
}
echo json_encode($responce);
}
this is the json what im seeing on firebug console
{"success":false,"data":{"error":"<p>The filetype you are attempting to upload is not allowed.<\/p>"}}</p>
any idea why its contain </p> and these <\/p> ?
Regards
According to the manual, $this->upload->display_errors() wraps the error messages in <p> tags.
You can pass parameters for the delimiters, to wrap the errors in what you want.
$this->upload->display_errors('', '');