File exceeds the defined ini size when using iframe - php

I am using fancy box iframe to display my page which has the file upload button. when i click form submit i got the "File exceeds the defined ini size". i checked some of links under google and stackoverflow. But not able to find. I have enctype="multipart/form-data" in my form. Following is my code
public function createForm($data = array())
{
$this->setMethod(Zend_Form::METHOD_POST);
$this->setEncType(Zend_Form::ENCTYPE_MULTIPART);
$this->setAttrib('id', 'createsub');
$this->setAction(
$this->getView()->getHelper('url')->url(array(
'controller' => 'test',
'action' => 'create'
))
);
$this->setDecorators(array(
'Description',
'FormElements',
'Form'
));
$fnameNotEmpty = new Zend_Validate_NotEmpty();
$fnameNotEmpty->setMessage('Name cannot be empty.');
$fnameStrlen = new Zend_Validate_StringLength(1, 20);
$name = new Zend_Form_Element_Text('name', array(
'label' => 'Name:',
'value' => '',
'class' => 'text-size text',
'tabindex' => '1',
'required' => true,
'validators' => array(
array($fnameNotEmpty, true),
array($fnameStrlen, true)
),
'decorators' => $this->requiredElementDecorators,
'description' => '<img src="../../'.$baseurl.'/images/star.png" alt="required" />',
'filters' => array('StringTrim')
));
$this->addElement($name);
.... ..... .....
$brochure = new Zend_Form_Element_File('brochure', array(
'label' => 'Brochure:*',
'value' => '',
'class' => 'text-size text',
'tabindex' => '3',
'required' => true,
'filters' => array('StringTrim')
));
$this->addElement($brochure);
$submit = $this->createElement('button','addtbtn',array('class'=>'Test','label'=>'Create'));
$submit->setIgnore(true);
$this->addElement($submit);
return $this;
}
Also if i did not use iframe, I can able to upload my image...Very Strange.
I make the validation using Ajax by following code ,
<script type="text/javascript">
var Path="<?php echo $this->eurl; ?>"
$(function()
{
vReg=0
$("#addtbtn").click(function()
{
if(vReg == 1)
{
return true;
}
else{
var url = 'validateform';
var data = {};
$("input").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("select").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("textarea").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function(resp)
{
vError=""
for(id in resp){
oResp=resp[id];
for(key in oResp){
vError +=oResp[key]+"\n"
}
}
if(vError == ''){
vReg=1
$("#createform").attr('target','_top');
$("#createform").submit();
return true;
}
else{
$("#createform").attr('target','_self');
alert(vError)
return false;
}
},'json');
}
});
});
</script>
Also Has the following function in my controller
public function validateformAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
$p = new Admin_Model_DbTable_Test();
$p = $p->getData();
foreach($p AS $k => $v)
{
$p[$v['catid']] = $v['name'];
}
$form = new Admin_Model_Form_SubTest();
$f = $form->createForm(array('parents' => $p));
$f->isValid($this->_getAllParams());
$json = $f->getMessages();
echo Zend_Json::encode($json);
}
So this will call the function which i gave on the top of the post and do the validation and return the error.But here i always getting "File exceeds the defined ini size " What I done wrong this code.
Kindly help me on this.

Check the upload_max_filesize setting in your .ini file(s). That's where this error comes from.

When you call .val() on your file input, you get the path of the file you have selected, while your validator will be expecting the file itself, hence the strange error. Most people opt to skip file inputs when doing ajax validation, and just check it on submit.

Related

working with PHP notice Undefined variable

I am trying to fix this for while but I can't. I found several tutorials but I couldn't fix it.
My friend and I are working on the same version, and it works on his PC without any problem - but for me it won't. We are using the same files, I copied mine from him.
What is the matter here and why won't this work on my PC?
Here is my index.php
<?php
/* #var $this SystemManagementController */
/* #var $dataProvider CActiveDataProvider */
?>
<?php
$this->breadcrumbs = array(
Yii::t('mainmenu', 'System Management'),
);
$contentTabUsers = $this->renderPartial('_tab_users', array(
'model' => $userModel,
'columns' => $userColumns,
), $return = true);
$contentTabStates = $this->renderPartial('_tab_states', array('model' => $stateModel), $return = true);
$contentTabPriorities = $this->renderPartial('_tab_priorities', null, $return = true);
$contentTabProperties = $this->renderPartial('_tab_properties', null, $return = true);
$upgradeLog = 'tbd'; //new UpgradeLog();
$systemInfo = new SystemInfo();
try
{
$systemInfoData = array(
'System Info' => $systemInfo->getServerInfo(),
'Apache' => $systemInfo->getApacheInfo(),
'MySQL Info' => $systemInfo->getMysqlInfo(),
);
}
catch (Exception $ex)
{
Yii::log('Could not retrieve system info, exception thrown with message: ' . $ex->getMessage(), CLogger::LEVEL_ERROR);
$systemInfoData = array();
}
$contentTabSysinfo = $this->renderPartial('_tab_sysinfo', array(
// 'model' => $upgradeLog,
// 'upgradeLogDataProvider' => $this->getUpgradeLogDataProvider(),
// 'upgradeScripts' => $this->getAllInfoUpgradeScripts(),
'systemInfo' => $systemInfoData,
'phpinfo' => $this->getBasicPhpInfo(),
), $return = true
);
// get the filter value to show max lines
$showMaxLines = (int) $this->getAppRequest()->getParam('log_show_max_lines', 50);
$contentTabLog = $this->renderPartial('_tab_log', array(
'applicationLog' => $this->getLog($showMaxLines),
'showMaxLines' => $showMaxLines,
// 'log_show_max_lines' is a placeholder for the js value in the template
'filterUrl' => $this->getYiiApp()->createUrl('systemManagement/index', array('log_show_max_lines' => null)),
), $return = true
);
Yii::app()->user->setState('activeSystemmanagementTab', 'system_info');
$tabs = array();
if (Yii::app()->user->checkAccess('Systemmanagement.users'))
{
$tabs[Yii::t('systemmanagement', 'Users')] = array('content' => $contentTabUsers, 'id' => 'users');
}
if (Yii::app()->user->checkAccess('Systemmanagement.states'))
{
$tabs[Yii::t('systemmanagement', 'States')] = array('content' => $contentTabStates, 'id' => 'states');
}
if (Yii::app()->user->checkAccess('Systemmanagement.priorities'))
{
$tabs[Yii::t('systemmanagement', 'Priorities')] = array('content' => $contentTabPriorities, 'id' => 'priorities');
}
if (Yii::app()->user->checkAccess('Systemmanagement.properties'))
{
$tabs[Yii::t('systemmanagement', 'Properties')] = array('content' => $contentTabProperties, 'id' => 'properties');
}
if (Yii::app()->user->checkAccess('Systemmanagement.sysinfo'))
{
$tabs[Yii::t('systemmanagement', 'System Info')] = array('content' => $contentTabSysinfo, 'id' => 'system_info');
}
if (Yii::app()->user->checkAccess('Systemmanagement.log'))
{
$tabs[Yii::t('systemmanagement', 'Log')] = array('content' => $contentTabLog, 'id' => 'log');
}
$this->widget('zii.widgets.jui.CJuiTabs', array(
'tabs' => $tabs,
// additional javascript options for the tabs plugin
'options' => array(
'collapsible' => true,
'hide' => 'fade',
'activeTab' => Yii::app()->user->getState('activeSystemmanagementTab'),
// 'show' => 'highlight',
//TODO #see http://www.bsourcecode.com/2012/11/how-to-handle-cjuitabs-in-yii/
'selected' => isset(Yii::app()->session['tabid']) ? Yii::app()->session['tabid'] : 0,
'select' => 'js:function(event, ui) {
var index=ui.index;
$.ajax({
"url":"' . Yii::app()->createUrl('site/tabidsession') . '",
"data":"tab="+index,
});
}',
)
)
);
?>
<script type="text/javascript">
function changeIsactive(id)
{
$.ajax({
type: 'post',
url: "<?php echo Yii::app()->createUrl('usp/AjaxSetuspOnOff') ?>",
datatype: 'json',
data: "MeId=" + id,
success: function (data) {
// if page access denied show the error msg
var hasError = $("<div></div>").append(data).find("#content div.error").length > 0;
if (hasError)
{
$("#flashmsg").show().addClass('flash-error').html('<?php echo Yii::t('systemwide', 'You Are Not Authorized to Turn On/Off this ELement'); ?>').animate({opacity: 0.9}, 3500).fadeOut("slow");
return false;
} else {
if (data != 'error')
{
if (data)
{
$('#onOff_' + id).addClass(data);
}
else {
$('#onOff_' + id).removeClass('checked');
}
}
else
{
$("#flashmsg").show().addClass('flash-error').html('<?php echo Yii::t('systemwide', 'You Are Not Authorized to Turn On/Off this ELement'); ?>').animate({opacity: 0.9}, 3500).fadeOut("slow");
}
return false;
}
},
error: function (jqXHR, exception) {
$("#flashmsg").show().addClass('flash-error').html('<?php echo Yii::t('systemwide', 'You Are Not Authorized to Turn On/Off this ELement'); ?>').animate({opacity: 0.9}, 3500).fadeOut("slow");
}
});
}
</script>
when I go to the server I get this error:
PHP notice Undefined variable: tabs /var/www/private/protected/views/systemmanagement/index.php(84)
and that is referring to :
'tabs' => $tabs,
in order to fix this I added, the following also on top of my file:
$tabs = array();
Now when I do this, it works and it doesn't give any error, but it just goes to the page and it doesn't show any content. Please help I am spending too much time on this.
if I put this in my code:
print_r($systemInfoData);
I get:
Array ( [System Info] => Array ( [OS] => Linux #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 [Machine Type] => x86_64 [Server Name] => 192.168.33.10 [Server IP Address] => 192.168.33.10 ) [Apache] => Array ( [version] => Apache/2.4.12 (Ubuntu) [Loaded Modules] => core, mod_so, mod_watchdog, http_core, mod_log_config, mod_logio, mod_version, mod_unixd, mod_access_compat, mod_alias, mod_auth_basic, mod_authn_core, mod_authn_file, mod_authz_core, mod_authz_groupfile, mod_authz_host, mod_authz_user, mod_autoindex, mod_cgi, mod_deflate, mod_dir, mod_env, mod_expires, mod_filter, mod_headers, mod_include, mod_mime, prefork, mod_negotiation, mod_php5, mod_reqtimeout, mod_rewrite, mod_setenvif, mod_status ) [MySQL Info] => Array ( [Server version] => 5.5.43-0ubuntu0.12.04.1 [Meta information] => Uptime: 11334 Threads: 1 Questions: 11476 Slow queries: 0 Opens: 76 Flush tables: 1 Open tables: 54 Queries per second avg: 1.012 ) )
The problem is caused by the variable $tabs not being defined.
You have two options, as rightly mentioned by the other contributos:
I. (preferable)
Define you variable before using it.
II. (not recommended)
The error is not shown on your friend's PC because of the error_reporting level set in his/her environment. Edit the error_reporting level defined in your php.ini.
In order to hide the php notices add or edit the following line in the php.ini
error_reporting = E_ALL & ~E_NOTICE;
Alternatively you can set your error reporting level directly from your script as follows:
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
Read more about error reporting in php here: http://php.net/manual/en/function.error-reporting.php
You are getting the Undefined variable error because your $tabs variable is not defined.
You have multiple if statements that could define it, but if they all evaluate to false, it will remain undefined.
Setting $tabs = array(); defines your variable, but it still has no content.

CakePHP: File replacement doesn't work

I'm very new on cakephp and I try to make an edit function with file replacement but it isn't working. If the file already exists I get an error message.
This is my admin_edit.ctp code:
<td>
<?php if (!empty($this->data['Stock']['filepath'])): ?>
<div class="input">
<label>Uploaded File</label>
<?php
echo $this->Form->input('filepath', array('type'=>'hidden', 'label' => false));
echo $this->Html->link(basename($this->data['Stock']['filepath']),
$this->data['Stock']['filepath']);
?>
</div>
<?php else: ?>
<?php echo $this->Form->input('filename',array('type' => 'file', 'label' => false)); ?>
<?php endif; ?>
</td>
here below stock.php validation code
public $validate = array(
'filename' => array(
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::uploadError
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload - filename error',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::mimeType
'mimeType' => array(
'rule' => array('mimeType', array('image/gif','image/png','image/jpg','image/jpeg')),
'message' => 'Invalid file, only images allowed',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// custom callback to deal with the file upload
'processUpload' => array(
'rule' => 'processUpload',
'message' => 'Something went wrong processing your file - process error',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
)
processUpload :
public function processUpload($check=array()) {
// deal with uploaded file
if (!empty($check['filename']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['filename']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['filename']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['filename']['name'], PATHINFO_EXTENSION);
// #todo check for duplicate filename
// try moving file
if (!move_uploaded_file($check['filename']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
}
}
return TRUE;
}
Error message :"Something went wrong with the file upload - filename error"
Before saving :
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['filename'] = $this->data[$this->alias]['filepath'];
foreach (array_keys($this->hasAndBelongsToMany) as $model){
if(isset($this->data[$this->name][$model])){
$this->data[$model][$model] = $this->data[$this->name][$model];
unset($this->data[$this->name][$model]);
}
}
}
return parent::beforeSave($options);
Does anyone help me to find mistake ?
Thanks

cannot submit ajax autocomplete form by enter key

I'm trying to add feature to our corporate website (this module called 'userpasswords2' searches database of local mailsystem passwords). I'm using AJAX autocomplete and modification of the form.
I cannot submit the form by enter key. AJAX autocomplete works fine, but when I choose the user, the form can only be submitted by submit button.
I would like it to work like here https://api.drupal.org/api/drupal - user enters for example 'hook', chooses for example hook_menu, hits enter, then hits enter again and get the result!
So again - clicking submit button works fine, hitting 'enter' key doesn't work.
Googled a lot, the workarounds I've found doesn't work for me. Please help.
function userpasswords2_menu() {
$items = array();
$items['userpasswords2'] = array(
'title' => 'User passwords',
'page callback' => 'drupal_get_form',
'page arguments' => array('userpasswords2_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['userpasswords2/ajax_username_autocomplete_callback2'] = array(
'page callback' => 'ajax_username_autocomplete_callback2',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
);
return $items;
}
function userpasswords2_form($form, &$form_state) {
$form = array();
$form['user'] = array(
'#type' => 'textfield',
'#title' => t('Enter username'),
'#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
'#executes_submit_callback' => 'TRUE',
);
$form['box'] = array(
'#type' => 'markup',
'#prefix' => '<div id="box">',
'#suffix' => '</div>',
'#markup' => '<br>',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
'callback' => 'userpasswords2_callback',
'wrapper' => 'box',
),
'#value' => t('Submit'),
);
return $form;
}
function ajax_username_autocomplete_callback2($string = "") {
$matches = array();
if ($string) {
$result = db_select('my_domain_passwords')
->fields('my_domain_passwords',array('fullname','password'))
->condition('fullname', db_like($string) . '%', 'LIKE')
->range(0,10)
->execute();
foreach ($result as $user) {
$form['custom']['username'] = $matches[$user->fullname] = check_plain($user->fullname);
$form['custom']['password'] = check_plain($user->password);
}
}
drupal_json_output($matches);
}
function userpasswords2_form_validate($form, &$form_state) {
$username = $form_state['values']['user'];
$matches = array();
// select from database by fullname
$result = db_select('my_domain_passwords')
->fields('my_domain_passwords', array('fullname'))
->condition('fullname', db_like($username), 'LIKE')
->range(0,1)
->execute()
->fetchField();
if (!empty($username)) {
$form_state['custom']['username'] = $result;
$password = db_select('my_domain_passwords')
->fields('my_domain_passwords', array('password'))
->condition('fullname', db_like($username), 'LIKE')
->range(0,1)
->execute()
->fetchField();
$form_state['custom']['password'] = $password;
}
return $form;
}
function userpasswords2_callback($form, &$form_state) {
if ( (!empty($form_state['custom']['username'])) && (!empty($form_state['custom']['password'])) ) {
$output_string = $form_state['custom']['username'] . " : " . $form_state['custom']['password'];
} else {
$output_string = "No such user: " . $form_state['values']['user'];
}
$username = $form_state['custom']['username'];
$password = $form_state['custom']['password'];
$element = $form['box'];
$element['#markup'] = $output_string;
return $element;
}
If you remove your autocomplete, you can be able to submit by press enter. So the issue is in the autocomplete function. You need to patch the misc/autocomplte.js. Following is the patch, check out the link for more details.
case 13: // Enter.
case 27: // Esc.
this.hidePopup(e.keyCode);
if (e.keyCode == 13 && $(input).hasClass('auto_submit')) {
input.form.submit();
}
This could be help you https://www.drupal.org/project/drupal/issues/309088

Codeigniter form validation callbacks not working

Probably something simple, but heres my problem, I have implememnted a simple captcha into my user system, but I can't seem to use the callback form validation to check to see if the captcha is correct.
I store the answer in the users session, and on form validation I check if it is correct.
You can see it live here: http://77.96.119.180/beer/user/register
Please excuse any references to beer ;)
Here is my code:
$this->form_validation->set_rules('captcha', 'Image verification', 'trim|required|xss_clean|integer|callback_captcha_check');
Here is part of the form
// CAPTCHA
$random_word = rand(10000, 99999);
$vals = array(
'word' => $random_word,
'img_path' => './captcha/',
'img_url' => 'http://77.96.119.180/beer/captcha/',
'font_path' => './captcha/fonts/pdark.ttf',
'img_width' => '150',
'img_height' => 50,
'expiration' => 7200
);
$cap = create_captcha($vals);
// Store captcha answer in session
$this->session->set_userdata('captcha_answer', $random_word);
$content .= form_label('Please enter the numbers in the box to verify you are human (Hint: Only numbers will appear)', 'captcha');
$content .= '<div class="left" style="margin-left:20px;">' . $cap['image'] . '</div>';
$content .= form_input(array('name' => 'captcha', 'value' => '', 'class' => 'right', 'style' => 'width:75%; margin-top:5px;'));
And here is the callback function
public function captcha_check($str)
{
if ($str == $this->session->userdata('captcha_answer'))
{
// Captcha is correct
$this->form_validation->set_message('captcha', 'The %s was wrong, please try again');
return FALSE;
}
else
{
return TRUE;
}
}
your validation rules are reversed in your callback function. your return true and return false logic needs to be reversed.
just change your if statement to this:
if ($str != $this->session->userdata('captcha_answer'))

In drupal 6, How to process uloaded file in more than one steps?

I am writing custom module in drupal.
Aim is to :
1. Upload a csv file
2. Display its content in a tabular layout.
3. On confirmation, save it in database.
Problem I am facing:
I am unable to upload any file. I am not getting any thing in $_FILES, even if I upload or not. >> SOLVED
How do I split the process ? Suppose I succeed in uploading file [with your help indeed ;) ], and I save the file, suppose in drupal6/uploaded_data directory. How do I redirect to next page where I can read from file and show tabular data for confirmation.
Codes :)
menu hooks and all
function productsadmin_menu() {
$items['admin/settings/product-administration'] = array(
'title' => 'Product Administration',
'description' => 'Upload products data',
'page callback' => 'productsadmin_form',
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function productsadmin_form() {
return drupal_get_form('productsadmin_my_form');
}
This function is passed to drupal_get_form()
function productsadmin_my_form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['csv'] = array(
'#type' => 'file',
'#title' => 'Product Catalog',
'#description' => 'Product catalog in specified csv format',
'#required' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
Validation (The part which is not working is commented)
function productsadmin_my_form_validate($form, &$form_state) {
if($form_state['values']['csv'] == "") {
form_set_error('csv', t('Please input product catalog csv data'));
}
/* // Check if file is uploaded (Not working)
if ($_FILES['files']['name']['csv'] == '') {
form_set_error('csv', t('Please upload product catalog' . $rahul_vals));
}
*/
}
Submit action
function productsadmin_my_form_submit($form, &$form_state) {
/*
1. Move File to uploaded_dir
2. Change the header so that it is redirected to new page
*/
}
you shouldn't use $_FILES in drupal,use drupal api
I made this example for you to explain how to work with cvs
/**
* Form function
*/
function _form_cvs_import($form_state) {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['container'] = array(
'#type' => 'fieldset',
'#title' => t('CVS UPLOAD') ,
);
$form['container']['cvs_file'] = array(
'#type' => 'file' ,
'#title' => t('CVS FILE') ,
'#description' => t('insert your cvs file here') ,
) ;
$form['container']['submit'] = array(
'#type' => 'submit' ,
'#value' => t('SEND') ,
) ;
return $form ;
}
/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
$validators = array(
'file_validate_extensions' => array('cvs'),
);
if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
form_set_error('cvs_file', 'Please select the cvs file') ;
}else{ // the file is submitted another validation for extension
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ;
if($file->filemime != 'application/octet-stream' ) {
form_set_error('cvs_file', 'Extensions Allowed : cvs') ;
}
}
}
/**
* form submit
*/
function _form_cvs_import_submit($form, $form_state) {
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ; // this is the cvs file in the tmp directory
$file_handler = fopen($file->filepath, 'r') ; // open this cvs file
$line_num = 0 ;
$fields = array() ;
while(!feof($file_handler)) {
$line_num++ ;
$line = fgets($file_handler) ; // this is the line/row
$line_array = explode(",", $line); // array of row fields
$field_num = 0 ;
foreach($line_array as $field) {
$field_num++ ;
$fields[$line_num][$field_num] = str_replace('"', '', $field ); // E.g you can access second row and third field by $fields[2][3]
}
}
fclose($file_handler);
unlink($file->filepath);
}

Categories