When I am running on localhost, it is fine. After uploaded on server.one error thrown-i.e.
The upload destination folder does not appear to be writable.
This is my controller-
function do_upload()
{
$path = './uploads/';
chmod($path,0777);
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$this->load->library('form_validation');
$data = array('upload_data' => $this->upload->data());
$pic_path= 'uploads/'.$data['upload_data']['file_name'];
$this->form_validation->set_rules('txt_title','Title','trim|required|xss_clean');
$this->form_validation->set_rules('category', 'Select Category', 'callback_select_validate');
$this->form_validation->set_rules('description','Description','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
redirect('upload');
}
else{
$title =mysql_real_escape_string(htmlentities($this->input->post('txt_title')));
$category = $this->input->post('category');
$description = mysql_real_escape_string(htmlentities($this->input->post('description')));
$this->load->model('user');
$suc_mesg=$this->user->insertPic($pic_path,$category,$title,$description);
$this->load->view('upload_success', $suc_mesg);
}
}
}
This is my view page-
<?php
echo $error;
echo form_fieldset('Upload Category Pics');
echo form_open_multipart('upload/do_upload');
echo '</br>';
echo form_label('Title','title');
echo '<input type="text" size="30" name="txt_title" placeholder="Enter title to pic"/>';
echo '</br></br>';
echo form_label('Choose Category Pics', 'category');
$options = array(
'null' => '--Please Select--',
1 => 'Technology',
3 => 'Entertainment',
2 => 'Politics',
4 => 'Sports'
);
echo form_dropdown('category', $options, 'category');
echo "<br></br>";
echo form_label('Description','description');
$data = array(
'name' => 'description',
'id' => 'description',
'placeholder' => 'Enter description',
'rows' => '5',
'cols' => '40',
);
echo form_textarea($data);
echo '</br></br>';
echo form_label('Browse Pics','pics');
echo '<input type="file" name="userfile" size="20" />';
echo "<br></br>";
echo '<input type="submit" value="upload" />';
echo '</form>';
echo form_fieldset_close();
?>
I'm unable to find my bug,where exactly am wrong. is there anybody ready to help me plz?
If the folder is for loading files by users than permisision 777 is required.
It's up to you to validate what files are loaded through upload script. Also you can use .htaccess to alow or not alow certain files to be executed from that directory.
The documentation for upload in codeigniter it's pretty simple and intuitive. Also here you can look at some ways to validate the type of files that are uploaded http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
I changed my uploads folder on web server as writable, so now it seems working.
Related
[SOLVED]
I am having a problem in function in my controller. I want to upload a single image twice and save it in the same directory but have different file names.
Here's my form(view.php):
<form action="<?php echo base_url("process/testFunction"); ?>" enctype="multipart/form-data" method="post">
<input type="file" name="file_data" size="50" required>
<input type="hidden" name="user_id" value="<?php echo $this->session->userdata('user_id'); ?>" readonly>
<input type="hidden" name="purpose" value="Picture" readonly>
<input type="submit" value="Save Changes">
</form>
controller.php:
function testFunction(){
$userID = $this->input->post('user_id');
$purpose = $this->input->post('purpose');
$randomText = time();
if($purpose == "Picture"){
$uploadPath = "./uploads/images/";
$allowedTypes = "jpg|jpeg|png";
$maxSize = 10000000;
$fileName = "PP_".$userID.".jpeg";
$fileName2 = "PP_".$userID."_".$randomText.".jpeg"; //for backup
}
$config = array(
'upload_path' => $uploadPath,
'allowed_types' => $allowedTypes,
'max_size' => $maxSize,
'file_name' => $fileName
);
$configClone = array(
'upload_path' => $uploadPath,
'allowed_types' => $allowedTypes,
'max_size' => $maxSize,
'file_name' => $fileName2
);
$this->load->library('upload', $config);
$this->load->library('upload', $configClone);
if($this->upload->do_upload('file_data')){
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
}
What is currently happening in my code is. Although it uploads 2 same images. The file name with "Random Text" is not working.
[Solution]: controller file. I modified some lines.
Reference: Javier's answer below
$this->load->library('upload', $config);
if($this->upload->do_upload('file_data')){
unset($this->upload);
$this->load->library('upload', $configClone);
$this->upload->do_upload('file_data');
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
Loading the upload library twice in a row, even with different configuration arrays, won't do anything. Codeigniter will ignore the second $this->load->library(); statement if the library is already on memory. This is intended to prevent conflicts, race conditions, etc.
You'd need to:-
load the first instance of the library
process the first upload
unload the first instance of the library
load the second instance of the library
process the second upload
Point number 3 could for example be achieved using unset($this->upload); after processing the first upload.
Remove this line
$this->load->library('upload', $configClone);
Change
if($this->upload->do_upload('file_data')){
$this->upload->initialize($configClone);
if($this->upload->do_upload('file_data')){
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
}else{
echo $this->upload->display_errors();
}
Explanation: Javier Larroulet's answer
//views/myproject/testupload.php
<a class="btn pull-right btn btn-primary"
href="<?= site_url("myproject/upload/") ?>"><?= lang('upload') ?></a>
//views/myproject/upload.php
<?php echo form_open_multipart(site_url('myproject/do_upload'));?>
<?=form_line('', form_upload('userfile', $this->form_validation->set_value('userfile')));?>
<?=form_submit('upload', lang('action_upload'), 'class="btn btn-primary"');?>
<?php echo form_close();?>
//Controller/myproject/test.php
public function upload()
{
$this->output->view('analytics/kysim/upload');
}
public function do_upload()
{
$config['upload_path'] = 'C:/test/';
$config['allowed_types'] = 'txt';
$this->load->library('upload', $config);
$name_file = $_FILES['userfile']['name'];
if ( ! $this->upload->do_upload($name_file))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die();
//$this->load->view('upload', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
var_dump($data);
die();
//$this->load->view('success', $data);
}
}
I am not able to upload a file to a specified location(C://test).var_dump($name_file) displays the uploaded file name.
$this->upload->do_upload($name_file) returns false and so var_dump($error) displays the error message "error" => "<p>You did not select a file to upload.</p><p>You did not select a file to upload.</p>""
Any help on uploading the file to specified location(C://test) would be appreciated.
Hope this will help you :
Note : make sure your c drive has test folder which in turn have writable permission
Your do_upload method should be like this :
public function do_upload()
{
$config['upload_path'] = 'C:\test\\';
$config['allowed_types'] = 'txt';
$this->load->library('upload', $config);
if (! empty($_FILES['userfile']['name']))
{
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die();
}
else
{
$data = array('upload_data' => $this->upload->data());
var_dump($data);
die();
}
}
}
Your form should be like this :
<?php
echo form_open_multipart('myproject/do_upload');
echo form_line('', form_upload('userfile', $this->form_validation->set_value('userfile')));
echo form_submit('upload', lang('action_upload'), 'class="btn btn-primary"');
echo form_close();
?>
For more : https://www.codeigniter.com/user_guide/libraries/file_uploading.html
This tutorial might help you:-
https://www.formget.com/codeigniter-upload-image/
Note is that : All data is inserted properly.
But if i'm upload an image with the help of
$this->upload->do_upload();and validate id,
this is not properly working. can u suggest..
//Controller
public function saveEmployeea()
{
$config = [ 'upload_path'=>'./uploads',
'allowed_types'=>'gif|jpg|png|jpeg'];
$this->load->library('upload', $config);
$this->form_validation->set_rules('dept_name', 'Department', 'required');
$this->form_validation->set_rules('firstname', 'First Name','required');
$this->form_validation->set_rules('middlename', 'Middle Name','required');
$this->form_validation->set_rules('lastname', 'Last Name','required');
$this->form_validation->set_rules('gendar', 'Gendar','required');
$this->form_validation->set_rules('address1', 'Local Address','required');
$this->form_validation->set_rules('address2', 'Permant Address','required');
$this->form_validation->set_rules('nationality', 'Nationality','required');
$this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');
$this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');
// $this->form_validation->set_rules('profile_image', 'Please Upload image','required');
$this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');
$this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
$this->form_validation->set_rules('personal_no', 'Personal Contact No','required');
$this->form_validation->set_rules('emergency_no', 'Emergency No','required');
$this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');
$this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');
$this->form_validation->set_rules('university', 'University','required');
$this->form_validation->set_rules('no_experience', 'No Experience','required');
$this->form_validation->set_rules('pre_compony', 'Previus Compony','required');
$this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
$this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');
if ( $this->form_validation->run() && $this->upload->do_upload())
{
$data = $this->input->post();
// insert images in data variables by using upload object oprater.
$upload_info = $this->upload->data();
//set path for images store
$path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);
$data['profile_image'] = $path;
// echo '<pre>';
// print_r($data);
// echo '</pre>';
// var_dump($data);
// exit();
// Load Model to Call Model class
$this->load->model('Loginm');
if($this->Loginm->insertEmployee($data))
{
$this->session->set_flashdata('employee_details','Employee Details Added Successfully');
}
else
{
$this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
}
return redirect('Employee/EmployeeList');
}
else
{
$upload_error = $this->upload->display_errors();
$this->createEmployee();
}
}
// Model
public function insertEmployee($data)
{
return $this->db->insert('employee',$data);
}`enter code here`
Try this code
$config['upload_path'] = 'd:/www/project_name/uploads/'; //document root path
$config['allowed_types'] = 'jpg|gif|png';
$config['file_name'] = $_FILES['profile_image']['name'];
//load upload class library
$this->load->library('upload', $config);
if (!$this->upload->do_upload('profile_image'))
{
// case - failure
echo $this->upload->display_errors();
}
else
{
// case - SUCCESS
}
First,
$this->upload->do_upload('userfile')
here 'userfile' in the name attribute in the input element.
<form action="url" enctype="multipart/form-data" method="post">
<input type="file" name="userfile" accept="image/*">
make sure you use:
enctype="multipart/form-data"
or
CI 3 counterpart:
echo form_open_multipart();
second,
The Upload Directory
You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter installation called uploads and set its file permissions to 777.
you may have file permission issue in the upload directory that you set. You should set proper permissions to the upload directory.
References:
https://www.codeigniter.com/userguide3/libraries/file_uploading.html
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.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have the following code witch I have just found out that I can upload any kind of file (.png.jpg .txt etc) but I am also unsure were to place $data[success] = TRUE so that it shows after the page has been reloaded and the functions have been run. How could I also do this with the error messages if there was an error?
Controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Addimage extends CI_Controller {
function __construct(){
parent::__construct();
}
function index() {
if(!$this->session->userdata('logged_in')) {
redirect('admin/home');
}
// Main Page Data
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = 'Add Gallery Image';
$data['content'] = $this->load->view('admin/addimage',NULL,TRUE);
$this->load->view('admintemplate', $data);
//Set Validation
//$this->form_validation->set_rules('userfile', 'userfile', 'trim|required');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
if($this->form_validation->run() === TRUE) {
//Set File Settings
$config['upload_path'] = 'includes/uploads/gallery/';
$config['allowed_types'] = 'jpg|png';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
$error = array('imageError' => $this->upload->display_errors());
}
else{
$data = array('upload_data' => $this->upload->data());
$data['success'] = TRUE;
$config['image_library'] = 'GD2';
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['new_image'] = 'includes/uploads/gallery/thumbs/';
$config['create_thumb'] = 'TRUE';
$config['thumb_marker'] ='_thumb';
$config['maintain_ratio'] = 'FALSE';
$config['width'] = '200';
$config['height'] = '150';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
$file_info = $this->upload->data();
$data = array(
'description' => $this->input->post('description', TRUE),
'imagename' => $file_info['file_name'],
'thumbname' =>$file_info['raw_name'].'_thumb'.$file_info['file_ext']
);
$this->image_model->addImage($data);
}
}
}
View:
<?php
//Setting form attributes
$formAddImage = array('id' => 'addImage', 'name' => 'addImage');
$imageImage = array('id' => 'userfile', 'name' => 'userfile', 'placeholder' => 'File Location*');
$imageDescription = array('id' => 'description','name' => 'description','placeholder' => 'Image Description*');
if($success == TRUE) {
echo '<section id = "validation">Image Uploaded</section>';
}
?>
<section id = "validation"><?php echo validation_errors();?></section>
<?php
echo form_open_multipart('admin/addimage', $formAddImage);
echo form_fieldset();
echo form_upload($imageImage);
echo form_textarea($imageDescription);
echo form_submit('submit','Submit');
echo form_fieldset_close();
echo form_close();
?>
if(!$this->upload->do_upload()) {
$status = array('imageError' => $this->upload->display_errors());
}
else
{
$status = 'Success message'; // or just true
// etc
}
then in your view:
if($status==TRUE)
{
// your success
}
else
{
// aw..somethings's gone wrong, print_r($status);
{
So essentially use one variable.
This is also a good example of when to use flashdata, which is exactly for these purposes.
if(!$this->upload->do_upload())
{
$this->session->set_flashdata('message', 'Sorry, error...');
}
else
{
$this->session->set_flashdata('message', 'Success!');
}
You can of course pass your array of data to set_flashdata if needed.