I'm creating a form to upload video file, but I have a strange error.
My form is like this:
<div style="color : red;"><?php echo $error;?></div>
<?php echo form_open_multipart('data_center/ajout_ressource/formulaire_video'); ?>
//various input text fields...
<input type="file" name="video">
<input type="submit" value="Ajouter cette ressource" />
</form>±
My method to get upload is (it's inside something to check if the rest of the form is ok):
$dir = './assets/video/';
$config['upload_path'] = $dir;
$config['allowed_types'] = 'avi|flv|wmv|mpeg|mp3|mp4';
$config['max_size'] = '102400';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('video')){
$error = array('error' => $this->upload->display_errors());
$this->load->view('data_center/ajout_video', $error);
} else {
redirect('data_center/data_center/','refresh');
}
Concerning mime types, I think it's ok:
'mp4' => 'video/mp4',
'wmv' => array('video/wmv', 'video/x-ms-wmv', 'flv-application/octet-stream', 'application/octet-stream'),
'flv' => array('video/flv', 'video/x-flv', 'flv-application/octet-stream', 'application/octet-stream'),
'avi' => 'video/x-msvideo',
When I try to upload a mp4 file it automatically redirect me (although I'm not sure it's a redirection) to the form, unfilled and no error message, even if I comment the lines in case of upload failure not to load the view again or if the rest of the form is uncorrect (it should not attempt to upload the video and load the form pre-filled).
Whereas for example, if I put the wrong type of file, I can see the error message ('The filetype you are attempting to upload is not allowed' for example), or if the form is wrong I can see the error of the form.
Finally, I must add that I modified php.ini to authorize such big files, and that I did pretty much the same thing with a form for pictures (jpg,jpeg,png...) which works perfectly but also redirect me to an unfilled form if I try to upload a .mp4 file.
Edit: I just downloaded an flv video to try, and it uploaded perfectly fine, but its size was less than 8mb (default config), and a 40mb flv file had the same problem as the mp4 file, although I changed my config in php.ini for 100mb
Efectively you have to change two parameters in PHP ini file
post_max_size = 100M
upload_max_filesize = 100M
But you may also want to change the apache abuse protection parameter (100M)
LimitRequestBody 1073741824
And by another hand, PHP have a time limit too of 30 sec per script, so your script will die at 30 seconds of running.
You may also want to increase the time to be sure your script does not die meanwhile you are uploading, copying etc,
set_time_limit(600); // 10 minutos execution
Related
I want to have a small upload limit (e.g. 100 kb for testing, perhaps 6 Mb ultimately). The size of the upload can be checked:
before the upload
fail when too much is uploaded
after the upload
If the user is trying a 1 Gb file ideally (1) should happen so that the file isn't uploaded at all. If not, (2) should happen so that it doesn't take long before the user knows the file is too big. I'd like to avoid the other possibility (3).
In HTML5 but not in IE9 the filesize can be checked before uploading using:
this.files[0].size
Get file size before uploading
In IE9 the following might work if the security settings are adjusted:
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
Ideally I'd like to use a method that works with IE9. I've heard about flash files being used. I'd like a method that is separate - not using a big plugin.
Here is my code. At the moment it uploads the whole file before it checks if the file size is too big.
<?php
if (isset($_FILES['myfile'])) {
if ($_FILES['myfile']['error'] == UPLOAD_ERR_FORM_SIZE) {
// $_FILES['myfile']['size'] is 0
echo 'Error: file is too big!<br>';
}
else if ($_FILES['myfile']['size'] > 100000) {
echo 'File size is too big!<br>';
}
else {
echo 'File uploaded ok.<br>';
}
}
var_dump($_FILES);
?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="myfile" />
<input type="submit" value="Submit" />
</form>
The small upload limit is just for one form so I don't want to change the global PHP settings file.
I'm not sure using MAX_FILE_SIZE is a good idea - the person still has to upload the entire file and the filesize data is lost (I might want to tell people how big their upload was)
ini_get('post_max_size') returns 8M and ini_get('upload_max_filesize') returns 32M. If files that are over 8 Mb try to be uploaded the file is still fully uploaded (even 40+ Mb). After larger than 8 Mb files are uploaded var_dump($_FILES) returns an empty array.
If the file is bigger than about 600 Mb I get a 413 error... that is (1).
So I want to do (1) or (2) in IE9, PHP and jQuery.
I want to allow only PDF and MS word files and size must be less than 2MB,
here is my code:
$mimes = array(
'application/pdf',
'application/x-pdf',
'application/acrobat',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
);
if(!in_array($_FILES['file']['type'], $mimes)) {
$msg1='<div class="alert alert-error">Invalid file format, Please choose only PDF or MS word files</div>';
} elseif($_FILES['file']['size']>2097152){
$msg2='<div class="alert alert-error">The file is too large,(must be < 2MB)</div>';
}
My problem is:
When I choose pdf file with size >2MB $msg1 is displayed instead of $msg2
I want to show $msg1 when file is not PDF or MS Word file ,
and $msg2 when file is >2MB
any help plz????
If u have
<form ...>
<input id='upload' name='upload'>
</form>
You must test $_FILES['upload']['size'] > 2097152
This is because.. Your first condition become wrong when you uploads the pdf file. when you trying to upload a file with greater than 2M size,
$_FILES['file']['type']
returns a null value. The reason lies in your php.ini file. go and find the line 'upload_max_filesize'. it will be probably sett to 2M.so due to this the type returns an empty string.
I have a file uploading function on my Symfony2 project.
I am seting the maxSize parameter like that:
$manuscript_file = new File(array(
'maxSize' => '20M',
'mimeTypes' => array(
'application/msword',
'application/zip',
),
'mimeTypesMessage' => 'Please upload a valid manuscript file. Valid types are: doc, docx, zip',
));
The problem is that when I am trying to upload a 2M or 3M word file, I am getting the validation message:
The file is too large. Allowed maximum size is 20M bytes.
Did you faced that? Or is my code wrong.
I took the example from the Symfony documentation:
Symfony File - Validation Constraints Reference
I already faces this issue, so I post this solution (I think this is the same issue for you).
This is a known bug of Symfony, in fact the framework will display the validator error message also when the file size is too high for your PHP configuration, instead of getting the classical PHP error.
In your current PHP config, you probably limited the max upload size to 2M, so Symfony display the wrong error.
So check your php.ini file (/etc/php5/apache2/php.ini on Linux) and increase max_upload_size to fit your field :
upload_max_filesize = 20M
Don't forget to restart apache : apache2ctl restart
Now it should work !
Note that's probably fixed on the last Symfony version, another solution is perhaps to upgrade your project to sf2.3 (but i'm not sure of that) ^^
I created a jQuery validation method to prevent sending big files to server because php don't valide it (It is in Spanish):
$(function() {
//Validate 20MB
validarFileSize('#carga_telefonos_form_file', {{ 10*1024*1024 }}, '#div-mensaje-file-size', '#botonSubmit');
});
function validarFileSize(campo, maximo, divMensaje, btnGuardar) {
console.debug("validarFileSize. Campo: " + campo + ", maximo: " + maximo);
$(campo).bind('change', function() {
var size = this.files[0].size;
if (size > maximo) {
$(divMensaje).show();
$(btnGuardar).attr('disabled', 'disabled');
} else {
$(divMensaje).hide();
$(btnGuardar).removeAttr('disabled');
}
});
}
If you are using POST to upload your file, beware with post_max_size limit in php.ini
I'm experiencing a very odd upload problem. Here's the relevant view file:
<form action="http://localhost/index.php/temp/upload/" method="post" enctype="multipart/form-data">
<fieldset>
<input type="file" name="userfile"/>
<input type="submit" value="Upload"/>
</fieldset>
</form>
And here's my temp controller's upload() method:
public function upload()
{
$config['upload_path'] = FCPATH . 'uploads' . DIRECTORY_SEPARATOR;
assert(file_exists($config['upload_path']) === TRUE);
$config['allowed_types'] = 'avi|mpg|mpeg|wmv|jpg';
$config['max_size'] = '0';
$this->load->library('upload', $config);
if ($this->upload->do_upload('userfile') === FALSE)
{
// Some error occured
var_dump($this->upload->display_errors('', ''));
var_dump($_FILES);
}
else
{
// Upload successful
var_dump($this->upload->data());
}
}
When I upload an AVI video, everything works fine. When I upload, say, a WMV video, I get the following var dumps:
string 'The filetype you are attempting to upload is not allowed.' (length=57)
array
'userfile' =>
array
'name' => string 'wmv.wmv' (length=7)
'type' => string 'video/x-ms-wmv' (length=14)
'tmp_name' => string 'C:\wamp\tmp\php2333.tmp' (length=23)
'error' => int 0
'size' => int 83914
The "wmv" extension is being interpreted as the MIME type: video/x-ms-wmv. This should be fine since my config/mimes.php has the following:
'wmv' => array('video/x-ms-wmv', 'audio/x-ms-wmv')
It's a similar situation when I try uploading other files. So far, the only one that seems to work is my test AVI video.
Any ideas what might be wrong?
UPDATE 1:
One my machine, only AVI uploads. On another developer's machine, no files upload. On yet another developer's machine, all supported files upload. Are these browser or server issues?
You are using Firefox, aren't you?
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Then do upload your .wmv file. It would show something like application/octet-stream or whatever. Add that to your mimes.php. Hope this help =)
Similar answer here
Some links:
CodeIgniter forum's thread
Mimetype corruption in Firefox
Getting around IE’s MIME type mangling
$config["allowed_types"] ="*";
Upload your .wmv file to the server using FTP/SFTP/scp/etc where you run the CodeIgniter application
On the server where you have uploaded the .wmv file, execute the following PHP code
<?php
$file_path = 'CHANGE_THIS_TO_ABSOLUTE_FILE_PATH_THAT_YOU_HAVE_UPLOADED.wmv';
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $file_path);
var_dump($mime);
?>
Save the code as mime.php
Run in the terminal - $ php mime.php
If it dumps any other value than you already have for wmv, append that value into wmv mime types.
Also check PHP_VERSION in other development machines. finfo_open is introduced in PHP 5.3. The development machine where upload is working may have an older version of PHP or it may have right mime type for the wmv.
did you try using mime types instead of extensions in $config['allowed_types']?
write it like this
$config["allowed_types"] = "video/x-msvideo|image/jpeg|video/mpeg|video/x-ms-wmv";
Answer for to Upload .doc file in CodeIgniter
Change this
'doc' => 'application/msword',
With this on line no 95 (application/config/mimes.php file)
'doc' => array('application/vnd.ms-word','application/msword'),
I've recently had some very similar problems with the Codeigniter's Upload Class.
The *allowed_types* doesn't seem to be working. For example, I wanted to allow .PNG images to be uploaded, but it wouldn't allow them through it's filter. I ended up investigating it further. I allowed all file types to be temporarily uploaded, I uploaded a .PNG, and then dumped the upload data ($this->upload->data());). For some reason, it thought the MIME type was text/plain! This might be related to your problem.
There are some solutions to this I found surfing some forums where you can modify/extend the class or core, but they didn't work for me -- sorry. I believe it's a Codeigniter Core bug (I think the issue has already been opened with EllisLabs). I ended up hard-coding the damn thing anyways! Well, I hope this helps you some.
Basic example/work-around,
//replace with your allowed MIME types
if ($_FILES['name_of_form_upload']['type'] != 'image/jpeg' && $_FILES['name_of_form_upload']['type'] != 'image/png' && $_FILES['name_of_form_upload']['type'] != 'image/gif') {
$data['message'] = '<div class="message">That file type is not allowed!</div>';
$this->load->view('home_view', $data);
} else {
//run upload code
}
Edit: Formatting/Grammar
Check your mimes.php file in application/config. It should return an array of mime types e.g return $mimes; at end of file or return array(..... in start of mimes array.
For Codeigniter 3.1.7 if you are providing a custom file name via $config['file_name'] ensure the filename has the file extension as well.
This is actually a bug in the core.. I upgraded to latest version of CI and the bug disappeared.
if you need the simple way to solve this,there is an easy solution for it.
open "system/libraries/Upload.php" file
line no 465
you will see
if ( ! $this->is_allowed_filetype())
{
$this->set_error('upload_invalid_filetype', 'debug');
return FALSE;
}
just make it true
if ( ! $this->is_allowed_filetype())
{
$this->set_error('upload_invalid_filetype', 'debug');
return TRUE;
}
note : it will stop your all file type validation.
Change IN application\config\Mimes.php
Inside my form i define this file upload field:
$this->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
$logo = $this->createElement('file', 'logo');
$logo->setLabel('Group logo')
->setMaxFileSize(5242880) // 5mb
->addValidator('IsImage')
->addValidator('Count', false, 1)
->addValidator('Size', false, 5242880)
->addValidator('Extension', false, array('jpg', 'jpeg', 'png', 'gif'));
However, no matter how small files I upload I get this error: File 'logo' exceeds the defined ini size.
The error message seemed pretty straight forward so I checked the php config (phpinfo() on the same exact page that handles the form)
file_uploads: On
upload_max_filesize: 2000M
memory_limit: 128M
post_max_size: 8M
While those values don't exactly make sense, they absolutely should allow me to upload files up to 8Mb but the upload always failes with the message from above. Even files smaller than 1Kb fail. I also tried removing all setters/validators but it still fails.
While searching for an answer I came across some posts that said that it was ajax' fault but this is a regular form, so now I'm stuck.
Update: I'm terribly sorry to have wasted your time, there was another unclosed form on the page which voided the multipart-declaration. Could have found that out sooner if I had tested with larger files rather than small ones :/
Add enctype="multipart/form-data" in your form. It should solve your problem.
Add
enctype="multipart/form-data"
to your <form> element. Solved my problem.
if you are using script file to render your file , you need to retrieve the enctype info that you specified in form class from your script file. <form enctype="<?php echo $this->element->getAttrib("enctype"); ?>">
Chances are that the php extension fileinfo is not activated.
Please check your php.ini file and increase upload_max_filesize. By default, it is 2M (2 MegaBytes). Also in order to be able to post file with size more than 2M you need to update value of post_max_size
It looks like you're missing the destination:
$logo->setLabel('Group logo')
->setDestination('/var/www/upload')
...
You might want to make sure that the folder is writeable by your web server.
When I commented out the following I got the same error:
->setDestination($this->_config->folder->ugc);
->addValidator(Kvadrat_Form_Element_File::VALIDATE_COUNT, true, 1);
->addValidator(Kvadrat_Form_Element_File::VALIDATE_SIZE, true, 5 * 102400);
(I commented it out as was doing the file uploads separately with FormData)
So I uncommented it and it all worked again.
Your size validator is incorrect. You should use this format:
->addValidator('Size', false, array('max' => '5242880'))
Your validator checks file's size == 5242880, NOT <= 5242880.