Im trying to make a file upload in CodeIgniter, how ever when I add enctype="multipart form-data" no post data will go through. At all not even the other fields. However when i dont add it, i can get the other post data, but of course no file upload. Whats going wrong here. Here is my view and controller:
View:
<h2>Add a New Album</h2>
<form enctype="multipart/form-data" method="post" action="<?php echo base_url();?>index.php/photo/newAlbum">
<table style="margin-left:5px;">
<tr>
<td> Album Name:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td> Photo .zip File:</td>
<td><input type="file" name="userfile" size="20" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload Photo File" /></td>
</tr>
</table>
</form>
controller only contains:
var_dump($_POST);
Result is:
array(0) { }
You can add this form attribute:
enctype="multipart/form-data;charset=utf-8"
Instead of:
enctype="multipart/form-data"
You can see this link.
Actually, the multipart data like image/zip or some other blob data will be included in $_FILES array, not $_POST array.
I recommend you to use the upload library.
view:upload_form.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
view:upload_success.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
controller:upload.php
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
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())
{
$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);
}
}
}
?>
And that's all
You need fix your do_upload, like this..
$this->upload->do_upload('name-of-input-file-element-of-your-form')
For example, in your view code, you have:
<input type="file" name="userfile" size="20" />
So, your do_upload line, should be like this:
$this->upload->do_upload('userfile')
Saludos!
Interesting. The code you posted should work. I made a quick test script using your form, and both the $_FILES and $_POST data come through fine.
I found this previous question on SO: PHP--parsing multipart form data
It sounds like the same problem you're having. Unfortunately no real answer was reached for that problem. I would think this might be a server configuration issue - can you try the same code on another server and see if it functions?
The only other bit of information I can find was in the answer to this question, $_POST data returns empty when headers are > POST_MAX_SIZE
If you are trying to upload too large a file, apparently that can cause PHP to throw away the $_POST data as well. But if you've tried submitting your form without uploading a file (but still using "multipart/form-data"), and still don't see any $_POST data coming through, that doesn't apply.
I just had the same problem.
I solved it this way. in application/config/config.php you set the base_url
please be aware of, that this url have to be exact the same as the one you're calling
your web app. For me, I called my domain with www.sdfsd.com, but in the config file
I wrote http://sdfsd.com and so the POST of the form didn't work. So I changed this
and now everything is working!!
cheers
Check for possible wrong redirection in CI layer. It could be caused by a wrong URL request (for example, a slash '/' missing at the end of the URL). Redirections delete any POST data (I was dealing with this).
So, be sure that you are using full URLs in form action.
Check for your .htaccess and $config['uri_protocol'] consistency too.
I had this problem too. I don't agree with the above answers. I think the crucial thing is at what stage in your controller you attempt to get the post data. Perhaps you could post the relevant part of your controller. I found that both the post data and the upload data only become available after you call
this->upload->do_upload()
Obviously, you use an if statement to check for success. If successful,
$this->upload->data()
returns the standard array with info about the uploaded file and
$this->input->post('name_of_your_form_element')
is populated with what you entered in the relevant form element.
I had a similar problem - Turns out POST data is empty when you exceed max upload size / max post size.
This answer fixed my problem and allowed me to see $_POST and $_FORM data:
$_POST data returns empty when headers are > POST_MAX_SIZE
Related
Context : I am updating user_profile data after user registration using form #updateprofileform ,
i am able to process all other form fields using standard validations and insert/update using user_model.
issue is with resume field which should accept a file as input type and upload to server and store its path on server (say http://domain/uploads/$filename) to a column in database.
Expectation A logged in user , able to view his details(if already in database),update details if incomplete profile.
Question : I found methods how we can upload a file to server using CI framework or how we can upload a file in this context using jquery/ajax/java-script. But i am looking for simple solution for above problem which can do the job with out dependency on technologies.
user_profile.php (view)
<table>
<form class="row" name="updateprofile" action = "<?php echo base_url()?>user/user_profile" method="POST">
<tr>
<td><label for="email">Email ID</label></td><td><input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php if (isset($email)) echo $email;?>" /> <span style="color:red"><?php echo form_error('email'); ?></span></td>
</tr>
<tr>
<td><label for="resume">Resume</label></td>
<td>
<input name="resume" placeholder="Upload resume" type="file" value="<?php if (isset($resume)) echo $resume;?>" />
<span style="color:red"><?php echo form_error('resume'); ?>
</span>
</td>
</tr>
<tr>
<td></td>
<td><div class="col-md-6 col-lg-3"> <button type="submit" class="btn btn--primary type--uppercase" name="updateprofile" value="updateprofile" formaction = "<?php echo base_url()?>user/user_profile">Update Profile</button> </div></td>
</tr>
</form>
</table>
user_controller
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "doc|docx|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
//'max_height' => "768",
//'max_width' => "1024"
);
$this->load->library('upload', $config);
}
public function user_profile()
{
$resume = $this->input->post('resume');
if ($this->user_model->set_user_profile($id,FALSE) )
{ if($this->do_upload($resume)){
$this->session->set_flashdata('msg_success','Updation Successful!');
echo validation_errors();}
}
else
{
$this->session->set_flashdata('msg_error','Error! Please try again later.');
redirect('user/user_profile');
}
public function do_upload($resume){
if($this->upload->do_upload($resume))
{
$data = array('upload_data' => $this->upload->data($resume));
$this->load->view('user_profile',$data);
}
else
{
$error = array('error' => $this->upload->display_errors($resume));
$this->load->view('user_profile', $error);
}
}
currently always error.... Error! Please try again later . so appreciate some pointers here to upload both file and form data together and save file location in database without ajax/jquery.
Thanks
Change the form definition to the following:
<form class="row" action = "<?php echo base_url('user/user_profile'); ?>" method="post" enctype="multipart/form-data" name="updateprofile" >
Resolved !
4 important steps needed and some missing in most Q&A in all other posts to make this complete.will share samplecode in github when i get sometime.
form encryption type must be enctype="multipart/form-data" (thanks
to #Javier Larroulet and #dexter )
do_upload method by default look for file field with name=userfile
(Thanks to #Alex ! for referencing this), so, if you have your
form's file field name different than userfile, then only it is
required to mention as do_upload('filefieldname') otherwise
optional
loading of upload library configuration is tricky.. if you
autoupload the upload library , then load->library upload config will fail!, you
just =>initialize it.$this->upload->initialize($config); if you
are not using autoload for upload library, then yes, you can load it
from controller. $this->load->library('upload', $config);
when ever, you are using upload, you have to catch the form validation errors
and data errors separately (again thanks to #Alex for pointing this)
a nice documentation is given from codeigniter at this link (https://www.codeigniter.com/userguide3/libraries/file_uploading.html#the-controller ) but doesn't highlight routine mistakes.
hope this post help someone not to waste another 24 hours to debug.
I am trying to upload a local file to webserver using HTML POST method and PHP.
this is my php code:
<?php
if (isset($_POST["submit"])) {
$updir = "/var/tmp/";
$upfile = $updir.basename($_FILES['rawexcel']['name']);
if(is_uploaded_file ($_FILES ["rawexcel"]["tmp_name"]))
{
move_uploaded_file ($_FILES["rawexcel"]["tmp_name"], $upfile);
} else {echo "error uploading file ".$upfile;}
} else {echo "not isset post method";}
?>
and HTML code is:
<div class="container" id="upl">
<h4> Upload files</h4>
<form action="upl.php" enctype="mutipart/form-data" method="post">
<p> upload your files to DB</p>
<p><input type="file" name="rawexcel" id ="rawexcel">
<input type ="submit" value="Upload" name ="submit"></p>
</form>
</div>
$_FILES["rawexcel"]["error"] shows 0 and from running this peice of code i get
error uploading file /var/tmp
I guess file name was not retrieved from html?
Error is in enctype:
enctype="multipart/form-data"
not:
enctype="mutipart/form-data"
You have typo mistake in enctype="multipart/form-data" , instead of this you typed enctype="mutipart/form-data" . So "mutipart" spelling is need to correct.
I'm having some trouble with CodeIgniter 2.1.4 and uploading files via AJAX.
I currently have a form which submits perfectly, like so (views/load_form):
<!--form created to add member to database -->
<?php echo form_open_multipart('index.php/member_record/add_member'); ?>
<?php echo form_fieldset('Create Membership Record'); ?>
<div class="container">
<form id="memberform" role="form">
<?php echo form_label('First Name', 'fname'); ?>
<?php echo form_input('fname'); ?>
</div>
<!--other such fields omitted for brevity-->
<label>Upload scanned ID Card</label>
<input type="file" name="scIDFile" id="scIDFile" />
<p class="help-block">Select image as either JPEG, GIF, PNG</p>
<input id="submit" type="submit" name="submit" value="Create Record" class="btn btn-success"/>
<!--end of view-->
I have a Controller which handled this well (controllers/member_record):
public member_record extends CI_Controller{
public add_member(){
$config['upload_path'] = './files/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size']= 1024*8;
$config['encrypt_name']=TRUE;
$config['overwrite'] =TRUE;
$this->load->library('upload',$config);
foreach($_FILES as $field => $file){
if($file['error'] == 0){
if($this->upload->do_upload($field)){
/*$image_config=array(
'source_image'=>$data['full_path'],
'new_image'=>$data['file_path'].'/thumbs',
'maintain_ratio'=>true,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib',$image_config);
$this->image_lib->resize();*/
}else{
$errors = $this->upload->display_errors();
}
}
}
}
}
And this was fine. However, due to certain new functionality that I'm adding to my view: I need to convert things to AJAX and pass all these values to the back-end through AJAX. I've been able to submit all of the fields (like first-name, last-name) to the backend via POST, however I'm struggling to enable file uploads!
I've tried using jQuery File Upload plugins, but there aren't very clear directions on how one would use them for CodeIgniter 2 (especially given my current code). If anyone can shed some light on this, I would appreciate it.
I'm working with php/html5 and i'm attempting to upload a file, but $_FILES['picture'] never seems to contain anything. I've been through a lot of posts and looked for common fixes, but none of them seem to work, firstly, the code;
Form;
<form enctype="multipart/form-data" action="decodeQR.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" name="picture" id="picture" value="picture" accept="picture/*" capture>
<input type="submit" value="Upload">
</form>
decodeQR.php;
<?php
include 'header.php';
$upload_status = FALSE;
if(isset($_FILES['picture']))
{
echo 'picture set <br>';
}
else
{
echo 'picture not set <br>';
}
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
if (isset($_FILES['picture']) && file_exists($_FILES['picture']['tmp_name']))
{
$image = $_FILES['picture']['tmp_name'];
//~ Check if image is an image
if (#getimagesize($image))
{
$upload_status = TRUE;
//~ from here you can use yours image as $_FILES['picture']['name'], for example to copy it
move_uploaded_file($image, realpath(dirname(__FILE__)).'/images/'.$_FILES['picture']['name']);
//~ Also be noticed that the image curently is in OS tmp folder and if you dont copy it, it will be deleted after script execution.
}
}
if ($upload_status)
{
echo 'Image successfully uploaded. <br> <img src="images/'.$_FILES['picture']['name'].'">';
}
else
{
echo 'nope.jpg';
}
?>
The output is always;
picture not set
nope.jpg
This means that $_Files['picture'] is not set, and there are no errors in the files array.
As you can see from the code above i have already tried the following fixes;
Added the markup for form enctype; enctype="multipart/form-data"
Added a hidden MAX_FILE_SIZE attribute
Not show in the code, i have tried adding size='30000000' in the file tag
I've checked that the value / name are the same when setting and getting file
I've also checked php.ini to ensure that file_upload is allowed
What could I possibly be missing?
Edit; I've tried this on my desktop and mobile browsers.
I found the solution to actually be a problem between the obvious (Not being able to file upload using ajax), and jquerymobile framework, which uses ajax on it's forms by default.
To fix the problem I added data-ajax='false'
<form enctype="multipart/form-data" action="decodeQR.php" method="post" data-ajax='false'>
The file upload works fine, so i'm posting this answer for anyone who's using jquerymobile and comes across this problem! : )
Have you checked if the request sent by the browser contains the file?
BTW. I'm new here. How do you guys add these "comments" to questions?
I'm having problems uploading files with CodeIgniter 2.1.0, as I recieve the $_FILES array empty.
This is the form:
<form enctype="multipart/form-data" action="<?= base_url()?>nicUpload/test" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
The action in the rendered form takes the value: http://localhost/nicUpload/test.
This is the controller:
<?php
class NicUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function test() {
echo count($_FILES);
}
}
?>
The result is 0, I would expect 1.
I tried doing the same without CodeIgniter:
index.php:
<!doctype html>
<html>
<head></head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
upload.php:
<?php
echo count($_FILES);
?>
and I get the expected result (1). So it's not a php configuration problem.
** UPDATE **
I should have said it earlier, but if I use CodeIgniter's Upload class it fails in this lines of CI's system/libraries/Upload.php:
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]))
{
$this->set_error('upload_no_file_selected');
return FALSE;
}
as $_FILES is empty.
Ok, thanks to Sena I found the problem. I was using the method described here to use i18n, so when I was uploading to http://localhost/nicUpload/test I was being redirected to http://localhost/spa/nicUpload/test, in that redirections the information in $_FILES was getting lost. So I just had to add nicUpload to the $special array in MY_Lang.php:
private $special = array (
"admin",
"auth",
"nicUpload"
);
That fixed it, once $_FILES had the proper information I could use the proper method to upload files (the method that Sena mentioned).