I have a form with few inputs and a file input.
I want to check whethere the file input is empty or not.
If it is empty do not try to upload, if it is not then try to upload it.
I tried something like this:
$upld_file = $this->upload->data();
if(!empty($upld_file))
{
//Upload file
}
you use codeigniter's file uploader class... and call $this->upload->do_upload(); in a conditional statement ahd check if its true.
<?php
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
The user_guide explains this in detail: http://codeigniter.com/user_guide/libraries/file_uploading.html
However,
if you are dead set on checking whether a file has been "uploaded" aka.. submitted BEFORE you call this class (not sure why you would). You can access PHPs $_FILES super global.. and use a conditional to check if size is > 0.
http://www.php.net/manual/en/reserved.variables.files.php
Update 2: This is actual working code, i use it on an avatar uploader myself using CI 2.1
<?php
//Just in case you decide to use multiple file uploads for some reason..
//if not, take the code within the foreach statement
foreach($_FILES as $files => $filesValue){
if (!empty($filesValue['name'])){
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}else{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}//nothing chosen, dont run.
}//end foreach
Probably do need more info. But basically, using the codeigniter upload class do something like this:
$result = $this->upload->do_upload();
if($result === FALSE)
{
// handle error
$message = $this->upload->display_errors();
}
else
{
// continue
}
There is a lot of functionality in codeigniter, probably don't need to re-invent the wheel here.
Related
I am trying to upload a .qif file in php codeigniter but it returns an error
The filetype you are attempting to upload is not allowed.
When I try to upload another type file (PDF, CSV, docs, etc.) they upload successfully.
Here is my code:
function do_upload($field_name, $files, $folder_path,$save_name="",$prefix="bk_"){
$ci = & get_instance();
//create upload folder if not exists
if (!is_dir($folder_path)) {
mkdir($folder_path, 0777, TRUE);
}
$save_name = $prefix.time()."_".$files['name'];
$data = array();
$config = array();
$config['upload_path'] = $folder_path;
//$config['max_size'] = 0;
$config['allowed_types'] = 'csv|CSV|txt|TXT|pdf|PDF|zip|ZIP|doc|DOC|docx|DOCX|xlsx|xls|XLS|XLSX|QIF|qif';
$config['file_name'] = $save_name;
$ci->load->library('upload');
$ci->upload->initialize($config);
// echo "hello 1"; die;
if ($ci->upload->do_upload($field_name)){
$data = $ci->upload->data();
$data['status'] = 1;
}
else{
$data['status'] = 0;
$data['error'] = $ci->upload->display_errors();
}
return $data;
}
You get the "filetype is not allowed" error, because the original Codeigniter mime-type configuration file doesn't list an qif entry:
in your config/mimes.php file add to the $mimes array this line:
'qif' => 'application/qif'
and eventually
'qif' => 'image/x-quicktime'
mime-type source: http://fileformats.archiveteam.org/wiki/Ext:qif
the native php move_uploaded_file method without checking for mime-types can turn into a security problem
I got a solution after lot of searches
I just use move_uploaded_file function and it's work
move_uploaded_file($_FILES["file"]["tmp_name"], $path);
if someone have a better answer answer please share that.
thanks
I want to upload a file in a certain file if a file is chosen from the input file tag
<input name="file1" type="file" id="addimage1">
I want to know how to deal it in models. I want to send the link of the image to the database.
When I was not using code-igniter I was doing this:
if(!empty($_FILES['file1']['name']) ) {
move_uploaded_file($_FILES["file1"]["tmp_name"],'assets/results/'.$myid.'/'. $_FILES["file1"]["name"]);
$link1='assets/results/'.$myid .'/' . $_FILES["file1"]["name"];
}
How can I do this in Code-igniter.
As user guide states:
//after uploading config
if ( ! $this->upload->do_upload('userfileinputname'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
//here add to db
$this->file_model->add_link_to_db($data['filename']);
$this->load->view('upload_success', $data);
}
}
And inside your model:
public function add_link_to_db($filename) {
return $last_id = $this->db->insert('mytable', ['name'=>$filename]);
}
I am trying to upload two files with the help of codeigniter functions.
One of the file should be mandatory and one should be optional.
I am using the code below to upload those files but I cannot figure out the way to make one optional and one mandatory. I tried few modifications to the code below, but i bumped into many errors. I am new to codeigniter.
Even the code below for handling the uploads may not be appropriate but it is working.
$config['upload_path'] = 'uploads/';
$path=$config['upload_path'];
$config['allowed_types'] = '*';
$this->load->library('upload');
$i=0;
foreach ($_FILES as $key => $value)
{
if (!empty($key['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($key))
{
$errors = $this->upload->display_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url().'upload', 'refresh');
}
else
{
$data = array('upload_data' => $this->upload->data());
$p[$i] = $this->upload->data();
}
}
$i++;
} //endforeach
if(empty($errors)){
//if there are no errors, write it into the database
$data = array('user_id'=>$this->session->userdata('id'),
'name'=>$this->input->post('name'),
'screenshot'=>$p[1]['file_name'],
'model'=> $p[0]['file_name'],
'created'=>date('Y-m-d H:i:s')
);
if($this->usermodel_model->save($data)){
//success
redirect(base_url().'dashboard?success');
}else{
//failed
redirect(base_url().'upload');
}
}
Sohanmax put $i++; inside if (!empty($key['name'])){ } and after ending foreach check if($i !=0) if it's false show the error, hope it'll work.
When the tmp directory is full, file_put_contents returns FALSE but the file is created with size of 0. file_put_contents should either complete the creation of the file or have no effect at all. For example:
$data = 'somedata';
$temp_name = '/tmp/myfile';
if (file_put_contents($temp_name, $data) === FALSE) {
// the message print that the file could not be created.
print 'The file could not be created.';
}
But when I go to the tmp directory, I can find the file "myfile" created in the directory with size 0. This makes it difficult to maintain. The file should not be created and I would like to see a message or warning the the tmp directory is full. Am I missing anything? And is this normal behaviors?
You are probably missing that if you do the error messages, you need to take care of that scenario, too:
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if ($success === FALSE)
{
$exists = is_file($temp_name);
if ($exists === FALSE) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}
This will also allow you to deal with it, like cleaning up if the transaction to write to the temporary file failed, to reset the system back into the state like before.
The problem is that file_put_contents will not necessarily return a boolean value and therefore your condition may not be appropriate you could try:
if(!file_put_contents($temp_name, $data)){
print 'The file could not be created.';
if(file_exists ($temp_name))
unlink($temp_name);
}
hi bro i found the Solution,
i know its old but its maybe help other people like me,
i was search about this code long time.
$data = 'somedata';
$temp_name = '/tmp/myfile';
$success = file_put_contents($temp_name, $data);
if (!$success){
$exists = is_file($temp_name);
if (!$exists) {
print 'The file could not be created.';
} else {
print 'The file was created but '.
'it could not be written to it without an error.';
}
}
Maybe I am missing something simple, but I can't seem to get my form verification just right.
How can I get the form validation to check the file verification too without doing an
$this->upload->do_upload("fldImage")
this is my verification process currently:
if ($this->form_validation->run() == FALSE)
{
if ( ! $this->upload->display_errors("fldImage"))
{
$error = array('error' => $this->upload->display_errors());
}
$this->load->view('submitBlog', $error);
}
else
{
if ( ! $this->upload->do_upload("fldImage"))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('submitBlog', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
unset($blog['submit']);
$imagePath = "uploads/".$data['upload_data']['file_name'];
$blog['fldImage'] = $imagePath;
$blog['fldDateAdded'] = $datetime;
$this->db->insert('tblBlog', $blog);
$this->load->view('submitBlogSuccess', $data);
}
}
but of course I can't call
do_upload("fldImage")
without running
do_upload()
but if the image is valid but the other form values are not, I do not want to upload the image.
First, add the following rule:
$this->form_validation->add_rule('userfile', 'required|callback__check_ext');
And the following callback function:
function _check_ext()
{
if ( ! empty($_FILES['userfile']['name']))
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$allowed = array('jpg', 'png');
if ( ! in_array(strtolower($ext), $allowed))
{
$this->form_validation->set_message('_check_ext', 'Extension not allowed');
return FALSE;
}
}
return TRUE;
}
Concept borrowed from PyroCMS. Alter where necessary.
Note: Checking for MIME-types is probably a better approach, let me know if you would like some help with that.
Well I hope I am not wrong in my answer. I have a similar issue. I wanted to be flexible with my website visitor. It means if a user wants to upload photo/file, it is ok, It not again it should not be any problem. Technically it was difficult for me to sort out whether the user has selected a file to upload or not. I search many forums and blogs and all over I find a solution which i want to share here. Please do let me know if I am wrong;
if(empty($_FILES['userfile']['name']))
{
// Perform the Normal Uploading without the File
}
else
{
// Perform the uploading with the File
}
It took me long to sort it out. If you find it not suitable way, Do let me know to correct my technique.