I have a dataTable with server-side processing but I don't know how to secure the ajax call because if anyone go to the ajax php file can read all the content.
This is my jquery:
$(document).ready(function() {
$('#netflow').DataTable( {
aaSorting: [[ 5, "desc" ]],
responsive: {
details: {
renderer: function ( api, rowIdx ) {
var data = api.cells( rowIdx, ':hidden' ).eq(0).map( function ( cell ) {
var header = $( api.column( cell.column ).header() );
return '<p style="color:#00A">'+header.text()+' : '+api.cell( cell ).data()+'</p>'; // changing details mark up.
} ).toArray().join('');
return data ? $('<table/>').append( data ) : false;
}
}
},
processing: true,
serverSide: true,
ajax: "/adm/includes/netflow_processing.php",
} );
var oTable = $('#netflow').dataTable();
var table = $('#netflow').DataTable();
$('#netflow_filter input').unbind();
$('#netflow_filter input').bind('keyup', function(e) {
if(e.keyCode == 13) {
oTable.fnFilter(this.value);
}
});
// Añadir filtro para cad acelda
$('#netflow tfoot th').each( function (i) {
$(this).html( '<input type="text"/style = "width: 100%; " placeholder="Filtra...">' );
} );
// Aplicar filtro al introducir en cada celda
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
} );
And this is the ajax script:
<?php
$table = 'netflow';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'flow_src', 'dt' => 0 ),
array( 'db' => 'flow_dst', 'dt' => 1 ),
array( 'db' => 'flow_proto', 'dt' => 2 ),
array( 'db' => 'out_packets', 'dt' => 3 ),
array( 'db' => 'in_packets', 'dt' => 4 ),
array( 'db' => 'flow_start', 'dt' => 5 )
);
$sql_details = array(
'user' => '6g43tfr3',
'pass' => 'XXXXXXXXX',
'db' => 'DBNAME',
'host' => 'bbdd.localdomain'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
How can I make a hash/token request?
You could simply check HTTP_REFERER. HTTP_REFERER is overwritten by the browser and cannot be altered meaning you cannot fake a request as it was called from within your script. So if name of the page (referer) that legally may access your script is
http://example.com/page42
(check what your script is called by echoing out $_SERVER['HTTP_REFERER']) then add
<?
if ($_SERVER['HTTP_REFERER'] != 'http://example.com/page42') {
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this script.');
}
...
as the very first lines to your /adm/includes/netflow_processing.php script.
First of all, I can't see any check that the user is logged, or some other check. You can create user with levels. Admin user, normal user and give him access code. You can use this pseudo code.
$access = false;
$user == isAdmin() {
$access = true;
}
if($access == false) return redirect;
Second, you can make some check that is AJAX requirest.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
}
And in this scopes you can make additional check ( for login, access level, etc. ) , BUT there's no 100% way to detect if the request was made via ajax. Even if someone sends header with
"X-Requested-With: XMLHttpRequest"
Related
Before I submit a form in WordPress, I try to pass some form values to a PHP script using jQuery Ajax to check whether similar posts already exist.
The first part of the jQuery works fine. However I am unsure, if the ajax passes the values to the PHP, because it always throws the alert('something went wrong');. I'm quite a bit lost, it's the first time, that I try to use Ajax.
jQuery(document).ready(function($) {
$('.madison').each(function(){
var _this = $(this) // get the loop item's div.madison
_this.find("select[name='trainingsort']").change( function() {
var _trainingsort = $("select[name='trainingsort']").val();
var vonzeit = "select[name='von-uhrzeit-" + _trainingsort + "']";
var biszeit = "select[name='bis-uhrzeit-" + _trainingsort + "']";
var _vonzeit = $(vonzeit).val();
var _biszeit = $(biszeit).val();
var _tag = $("input[name='tag']").val();
var _reitanlage_id = $("input[name='reitanlagen_id']").val();
var ort = _trainingsort + ' / ' + _vonzeit + ' / ' + _biszeit + ' / ' + _reitanlage_id + ' / ' + _tag;
alert( "Yes! " + ort );
_this.find("input[name='wpcf-rask-name-des-menschen']").val(ort);
// ----- everything works fine above this line ---------------------
$.ajax({
type: "POST",
url: "https://test.cuteberry.de/wp-content/toolset-customizations/trainingsanlagen-2-0__ajax-notification.php",
data: {trainingsort: _trainingsort, vonzeit: _vonzeit, biszeit: _biszeit, reitanlagen_id: _reitanlage_id, tag: _tag},
success: function(data){
alert(data);
},
error: function(data){
alert('something went wrong');
}
});
});
});
});
and the PHP ....
PHP:
<?php
/**
* New custom code snippet (replace this with snippet description).
*/
toolset_snippet_security_check() or die( 'Direct access is not allowed' );
// Put the code of your snippet below this comment.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$trainingsort=isset($_POST['trainingsort'])?json_decode($_POST['trainingsort']):null; $vonzeit=isset($_POST['vonzeit'])?json_decode($_POST['vonzeit']):null; $biszeit=isset($_POST['biszeit'])?json_decode($_POST['biszeit']):null;
$reitanlagen_id=isset($_POST['reitanlagen_id'])?json_decode($_POST['reitanlagen_id']):null; $tag=isset($_POST['tag'])?json_decode($_POST['tag']):null;
$response = "";
// ----- everything works fine below this line ---------------------
if (isset($reitanlagen_id) && !empty($reitanlagen_id)) {
for ($i = $vonzeit; $i <= $biszeit; $i++) {
// Warteliste_Posts suchen
$query = new WP_Query(
array(
'post_type' => 'rask',
'post_status' => 'publish',
'posts_per_page' => -1,
'toolset_relationships' => array(
'role' => 'child',
'related_to' => $reitanlagen_id,
'relationship' => 'reitanlage-rask'
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'wpcf-rask-ort-des-geschehens',
'value' => $trainingsort,
'compare' => '='
),
array(
'key' => 'wpcf-rask-welches-journal-termine',
'value' => 1,
'compare' => '='
),
array(
'key' => 'wpcf-rask-von-tag',
'value' => $tag,
'type' => 'numeric',
'compare' => '='
),
array(
'key' => 'wpcf-rask-von-uhrzeit-15-minuten',
'value' => $i,
'type' => 'numeric',
'compare' => '<='
),
array(
'key' => 'wpcf-rask-bis-uhrzeit-15-minuten',
'value' => $i ,
'type' => 'numeric',
'compare' => '>='
),
)
)
);
$pferde_posts = $query->posts;
$count = count($pferde_posts);
// ----- everything works fine above this line ---------------------
if ($count >= 0) {
$response = json_encode("existiert");
break;
}
}
}
echo $response;
I'm thankfull for any hints in the right direction : )
I would like to let the script do a redirection on click of the submit button by using the PHP header function. However, it doesn't seem to work. Any idea how i could get it to work with PHP header function?
Here's part of the function that i thought is relevant:-
switch ( $service ) {
case 'mailchimp' :
$lastname = sanitize_text_field( $_POST['et_lastname'] );
$email = array( 'email' => $email );
if ( ! class_exists( 'MailChimp' ) )
require_once( get_template_directory() . '/includes/subscription/mailchimp/mailchimp.php' );
$mailchimp_api_key = et_get_option( 'divi_mailchimp_api_key' );
if ( '' === $mailchimp_api_key ) die( json_encode( array( 'error' => __( 'Configuration error: api key is not defined', 'Divi' ) ) ) );
$mailchimp = new MailChimp( $mailchimp_api_key );
$merge_vars = array(
'FNAME' => $firstname,
'LNAME' => $lastname,
);
$retval = $mailchimp->call('lists/subscribe', array(
'id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
));
if ( isset($retval['error']) ) {
if ( '214' == $retval['code'] ){
$error_message = str_replace( 'Click here to update your profile.', '', $retval['error'] );
$result = json_encode( array( 'success' => $error_message ) );
} else {
$result = json_encode( array( 'success' => $retval['error'] ) );
}
} else {
$result = json_encode( array( 'success' => $success_message ) );
}
die( $result );
break;
I tried to replace the $result with header("Location: http://www.example.com/"); but it didn't work.
The reason that you can't just change the code to $result = header('Location: ...') is actually quite simple. With this javascript call as an example:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, function(data) {
// do something
});
What happens:
An HTTP-POST call is made via AJAX to /myscript.php
Your code is executed, subscribing the given email address.
The PHP code returns a 301
The AJAX call will follow the redirect, but your browser will stay on the same page.
What you actually want is that when the AJAX call was successful, the browser redirects to another page. To achieve that, you'll need to update both your PHP and Javascript.
In your PHP, you'll have to return the location you want the browser to redirect to, for example:
<?php
$result = json_encode(array('location' => 'https://example.com/path/to/page'));
Right now, the PHP script just returns an json-response with a location key. The browser, nor the javascript doesn't do anything with that information unless we tell it to do so:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, null, 'json').done(function(data) {
// do something ...
// redirect browser to page we provided in the ajax response
window.location = data.location;
}).fail(function(data) {
// handle the error
});
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.
I have two controllers:
test.php
public function trackback()
{
$this->load->library('trackback');
$tb_data = array(
'ping_url' => 'http://www.citest.com/addtrackback/receive/777',
'url' => 'http://www.citest.com/test/trackback/',
'title' => 'Заголовок',
'excerpt' => 'Текст.',
'blog_name' => 'Название блога',
'charset' => 'utf-8'
);
if ( ! $this->trackback->send($tb_data))
{
echo $this->trackback->display_errors();
}
else
{
echo 'Trackback успешно отправлен!';
}
}
function trackback() sends the trackback information
addtrackback.php
public function receive()
{
$this->load->library('trackback');
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
$data = array(
'tb_id' => '',
'entry_id' => $this->uri->segment(3),
'url' => $this->trackback->data('url'),
'title' => $this->trackback->data('title'),
'excerpt' => $this->trackback->data('excerpt'),
'blog_name' => $this->trackback->data('blog_name'),
'tb_date' => time(),
'ip_address' => $this->input->ip_address()
);
$sql = $this->db->insert_string('trackbacks', $data);
$this->db->query($sql);
$this->trackback->send_success();
}
function receive() gets trackback and writes it into a table called 'trackbacks' in the database.
But when I try to view the page, it results in the following error:
An unknown error was encountered.
What's causing this error?
are you referencing the library or the function you're in? if ( ! $this->trackback->send($tb_data))
try changing it to something like
public function trackback(){
$this->load->library('trackbackLibrary');
what are you trying to accomplish because it seems like you're attempting to do an if statement for the same process.
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
Also,
Check your error_log file to see what the actual error its throwing. /var/log or some other places. Depending on your OS
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.