I'm have a problem uploading a picture using codeigniter. I followed the online upload tutorial, but can't figure out the problem. I keep getting "The upload path does not appear to be valid". So, here's my form structure:
<?php if (isset($error)) {?>
<div class="col-md-12">
<div class="alert alert-danger" role="alert">
<?= $error ?>
</div>
</div>
<?php } ?>
<?php echo form_open_multipart('pages/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
I also checked for my directory to be a valid path and to be writable with this code:
<?php if(is_writable('./uploads') && is_dir('./uploads')){
echo 'valid';
}
else { echo (base_url('uploads'). ' ' ."is not writable");} ?>
And this returns valid.
The following is my controller structure:
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 10000000000;
$config['max_width'] = 1920;
$config['max_height'] = 1080;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('user/profile/profile', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
In construct i loaded the upload library.
With all this being said, I keep getting the error I mentioned before.
Try Using
$config["upload_path"] = $_SERVER['DOCUMENT_ROOT']."/your/desired/location/";
i'm trying to upload a file in databse using codeigniter, the image is getting stored in the folder but i'm having issue in storing the data in databse, i don know where
im going wrong. please can any one guide me what im doing wrong ? im new to codeigniter concept.
upload.php(controller)
<?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);
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$this->Upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
}
}
?>
Upload_model.php(model)
<?php
class Upload_model extends CI_Model
{
//Insert
function saverecords($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Upload_form.php(view)
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "POST">
<input type = "file" name = "filename" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
You declare <form> twice! Remove <form action = "" method = "POST"> completely and just use the above form_open_multipart:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="filename" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
Also there is no need for spaces like type = "submit"
Then in your code:
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
//$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$data['upload_data'] = $this->upload->data('file_name');
$this->load->model('upload_model');
$this->upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
For future:
Do not just do $this->input->post() to assign the key value pairs to those in db. It is not very controlled and can lead to issues. Instead just define it. So if you add other data it would look something like:
$data = array(
'example1_fieldname' => $this->input->post('example1_fieldname');
'upload_data' => $this->upload->data('file_name');
);
In CodeIgniter, I have 4 file upload controls as under:
<?php echo form_open_multipart('uploadimg');?>
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<input type="submit" value="upload" />
<?php echo form_close();?>
Following is my file upload code:
$name1="img1.jpg";
$config1=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name1,
);
$this->load->library('upload',$config1);
if($this->upload->do_upload('image1'))
{
echo "Image 1 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name2="img2.jpg";
$config2=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name2,
);
$this->load->library('upload',$config2);
if($this->upload->do_upload('image2'))
{
echo "Image 2 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name3="img3.jpg";
$config3=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name3,
);
$this->load->library('upload',$config3);
if($this->upload->do_upload('image3'))
{
echo "Image 3 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name4="img4.jpg";
$config4=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name4,
);
$this->load->library('upload',$config4);
if($this->upload->do_upload('image4'))
{
echo "Image 4 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
I am getting the following output:
Image 1 has been uploaded successfullyImage 2 has been uploaded
successfullyImage 3 has been uploaded successfullyImage 4 has been
uploaded successfully
But, in the uploads folder, I am getting only 1 file. Strange thing is that the file that is being shown is of last file upload control, but the name of file is img1., i.e. name of first uploaded file.
Why is this happening? What is the solution?
Set each config using the initialize() method and not when loading the upload library.
Changed:
$this->load->library('upload', $config*);
To:
$this->upload->initialize($config*);
Updated code:
$this->load->library('upload');
$name1 = "img1.jpg";
$config1 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name1
);
$this->upload->initialize($config1);
if ($this->upload->do_upload('image1')) {
echo "Image 1 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name2 = "img2.jpg";
$config2 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name2
);
$this->upload->initialize($config2);
if ($this->upload->do_upload('image2')) {
echo "Image 2 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name3 = "img3.jpg";
$config3 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name3
);
$this->upload->initialize($config3);
if ($this->upload->do_upload('image3')) {
echo "Image 3 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name4 = "img4.jpg";
$config4 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name4
);
$this->upload->initialize($config4);
if ($this->upload->do_upload('image4')) {
echo "Image 4 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
You may try this. This is working properly to upload two file
(audio, image) or more file to the database.
Table Name : products
| id | product_name | price | description| product_image | audio_file |
HTML
<form name="addProduct" id="addProduct" method="POST" enctype="multipart/form-data">
<input type="text" name="product_name" placeholder="Product Name">
<input type="text" name="price" placeholder="Product Price">
<textarea id="description" name="description" class="materialize-textarea" placeholder="Description"></textarea>
<input type="file" name="product_image" id="fileImg">
<input type="file" name="audio_file" id="audio_file">
<input type="button" name="addProduct" value="Add Product" class="btn btn-flat btn-add-product">
</form>
Controller
public function addProducts(){
/*Initialization of model*/
$this->load->model("product_model");
/*store data into array*/
$result=array(
"product_name"=>$_POST["product_name"],
"price"=>$_POST["price"],
"description"=>$_POST["description"],
);
$proID = $this->product_model->addProduct($result); //sending data to model for insertion
//Define the file names with blog id with same extension which has been uploaded
$product_image = $proID."_product.".pathinfo($_FILES['product_image']['name'], PATHINFO_EXTENSION);
$product_audio = $proID."_audio.".pathinfo($_FILES['audio_file']['name'], PATHINFO_EXTENSION);
$updateData = array(
"product_image" => $product_image,
"audio_file"=>$product_audio
);
// update the name of the images in the database
$this->product_model->updateProduct($updateData,$proID);
//set configuration for the upload library
/* |===> Image Config <==|*/
$config['upload_path'] = 'html/images/products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
/* |==> Audio Config <==|*/
$config_audio['upload_path'] = 'html/images/products/audios/';
$config_audio['allowed_types'] = 'mp3|mp4';
$config_audio['overwrite'] = TRUE;
$config_audio['encrypt_name'] = FALSE;
$config_audio['remove_spaces'] = TRUE;
//set name in the config file for the feature image
$config['file_name'] = $proID."_product";
$this->load->library('upload', $config); // config first file
$this->upload->do_upload('product_image');
$this->upload->display_errors();
$config_audio['file_name'] = $proID."_audio";
$this->upload->initialize($config_audio); // config seconf file
$this->upload->do_upload('audio_file');
$this->upload->display_errors();
}
Model
/*Add Product*/
public function addProduct($pro_data){
$query=$this->db->insert("products",$pro_data);
$id=$this->db->insert_id();
return $id;
}
/*Update for Multiple File Upload*/
public function updateProduct($result,$up_id){
$this->db->where('id',$up_id);
$this->db->update("products",$result);
}
This is working nicely to my website and i hope it will help you to boost your code.
HTML
<form class="col s12" id='propertyform' enctype="multipart/form-data">
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<a class="waves-effect waves-light btn addproperty">add</a>
</form>
js
$(".addproperty").on("click",function()
{
var baseurl = $("#base_url").val();
var property = new FormData($("#propertyform")[0]);
$.ajax({
url : baseurl+"dropdowns/add_propertyy",
data : property,
type:"POST",
contentType:false,
processData:false,
success:function(res)
{
window.location.reload();
}
});
});
controller
public function add_propertyy()
{
$id = 1;
$images = $id."_image1.".pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION);
$images1 = $id."_image2.".pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION);
$images2 = $id."_image3.".pathinfo($_FILES['images3']['name'], PATHINFO_EXTENSION);
$images3 = $id."_image4.".pathinfo($_FILES['image4']['name'], PATHINFO_EXTENSION);
$addimg = array(
"images1" => $images,
"images2" => $images1,
"images3" => $images2,
"images4" => $images3,
);
$this->load->model('property_model');
$this->property_model->add_pro_img($addimg,$id);
$uploadPath = "./html/images/property";
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = $id."_images1";
$this->load->library('upload', $config);
$this->upload->do_upload('images');
$this->upload->display_errors();
$config['file_name'] = $id."_images2";
$this->upload->initialize($config);
$this->upload->do_upload('images2');
$this->upload->display_errors();
$config['file_name'] = $id."_images3";
$this->upload->initialize($config);
$this->upload->do_upload('images3');
$this->upload->display_errors();
$config['file_name'] = $id."_images4";
$this->upload->initialize($config);
$this->upload->do_upload('images4');
$this->upload->display_errors();
}
modal
public function add_pro($data) {
$this->db->insert("property",$data);
$id = $this->db->insert_id();
return $id;
}
I want to upload file in folder, following is my code for upload file in folder, the code is successfully working in my local system and also file moved to folder but on server side i got 'The upload path does not appear to be valid'. when i used $config['upload_path'] = './uploads/'; but when i used $config['upload_path'] = './assets/images/store/category'; i got success message but uploaded file is not showing in category folder.
Following is my code.
Controller
<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
echo "Tst";
$this->load->view('Upload_form', array('error' => ' ' ));
}
public function Test_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);
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());
echo '<pre>';
print_r($data);
// $this->load->view('upload_success', $data);
}
}
}
?>
View ( form)
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/Test_do_upload');?>
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
<?= form_close(); ?>
</body>
</html>
View of success upload
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
Code is working in my local system but on server side file not move to folder. I also given permission.
I can see there are two form tag could fire this problem. So revise it
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<form action ="<?php echo site_url('upload/Test_do_upload');?>" method="post" enctype="multipart/form-data">
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
May be try this code and try to create directory if its not created. Else print $error variable to find out what kind of upload error. May be this will be helpful. And remove form tag from your view its repeated.
$dir_path= 'assets/admin/uploads/course_images/';
if (!is_dir($dir_path)) {
mkdir($dir_path, 0777, TRUE);
}
$new_name = time().$this->input->post('Course_code');
//move_uploaded_file($_FILES['file']['tmp_name'], $dir_path);
$config['upload_path'] = $dir_path;
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '1000';
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('file'))
{
// no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
/*Print Error*/
}else{
/*Insert Code*/
}
The issue here is, when I Upload videos, it works perfectly but not images which is giving me a hard time to figure out what the error may be
This is what the HTML looks like:
<form action="index.php" method="post" enctype="multipart/form-data" >
<h1>Browse for file to upload:</h1>
</div>
<div>
<label for="file"><h1><b>Select Video</b></h1></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<label for="file"><h2><b>Select Image</b></h2></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<input type="submit" value="Upload" name="submit">
</form>
The PHP Script looks like this:
$error = null;
$success = null;
$info = [];
$uploadOk = 1;
$allowedMimes = ['video/mp4', 'image/jpg'];
if(isset($_POST["submit"])) {
$counter = 0;
foreach ( $_FILES['fileToUpload1']['name'] as $file ):
$target_file = UPLOAD_DIR . basename($file);
if ( in_array(mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter]), $allowedMimes) ){
if (move_uploaded_file($_FILES['fileToUpload1']["tmp_name"][$counter], $target_file)) {
$info[] = "File ".++$counter."($file) uploaded successfully";
}else {
$info[] = "File ".++$counter."($file) cannot be uploaded";
}
} else {
$info[] = "File ".++$counter. " is not allowed.";
}
endforeach;
} else {
echo "upload a file.";
}
?>
<ul>
<?php foreach($info as $i){ ?>
<li><?=$i;?></li>
<?php }?>
</ul>
<? } ?>
The mimetype of jpg files is actually image/jpeg (and not iamge/jpg), so if you are trying to upload jpg files you should change your $allowedMimes variable to:
$allowedMimes = ['video/mp4', 'image/jpeg'];
Also - if you want to support other image types you can use:
$allowedMimes = ['video/mp4', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'];
Another option - if you want to support all image/audio/video types you can check only the first part of the string:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
array_shift(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)
),
$allowedTypes) )
If you are using php>=5.4 you can use:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)[0],
$allowedTypes) )