Firefox-extension corrupt gzip response - javascript

Firefox-extension: http://mikelsv.ru/extension_ci.xpi (update: var site_url="you site/php_code.php"; in chrome\content\accelerator.js )
PHP code: pastebin.com/hbSNfp1e
How work:
<br>
PHP: form method=post action=https://java.shadowlands.ru/zombievk/items?compress=true&lang=ru
extension: if(http-on-examine-response && url=='shadowlands...') new TracingListener();
<br>TracingListener.onDataAvailable(){ this.receivedData.push(data); }
<br>TracingListener.onStopRequest(){ send_post_data(this.receivedData.join()); to site_url; }
PHP: $postdata = file_get_contents("php://input");
<br> gzuncompress(base64_decode($data)));
Problem: gzip data corrupt. All ok if: form action=.../items?compress=true&lang=<b>en</b>
What do I need to do to fix this problem?

I have found the problem. I've omitted the separator argument of the .join method, so the default separator (,) was used. I have resolved the problem by providing an empty string as a separator:
var responseSource = this.receivedData.join();
becomes:
var responseSource = this.receivedData.join('');

Related

PHP $_POST cutting off '<' character coming from $.post in jQuery

I feel like this should be easy. The character < (and following characters) refuses to be sent to $_POST. My max_input_vars is set to 10000, my memory limit is set to 3GB in my php.ini file, and I'm using PHP 8.0.
I have a text area where the text gets posted to a PHP file.
# HTML
<div class="add-comment">
<textarea style="margin-left: -15px;" placeholder="Add your commentary here" style="white-space:pre-wrap;" id="add-comment" class="form-control" rows="3"></textarea>
</div>
# JS
let comment = $('#add-comment').val();
const post_variables = {
'comment' : comment
};
console.log(post_variables);
$.post('/?c=comments&a=add_comment', post_variables, function(data){});
# PHP
echo '<pre>post:<br>';
print_r($_POST);
echo '</pre>';
Lets say I submit the text 'a < b'.
In JS, the log shows: a < b
In PHP the log shows: a
Is there something I need to do before passing it off to PHP? I'm genuinely surprised I haven't run into this before..
You can print the "<" on PHP using print_r(htmlspecialchar($_POST['comment'])) and if you want to convert it before sending to PHP use below function
# JS
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g,'<').replace(/>/g, '>').replace(/"/g, '"');
}
let comment = $('#add-comment').val();
const post_variables = {
'comment' : htmlEntities(comment)
};

JSON.parse() not working even though JSON string is valid

I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}
don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
<img src="+"img/loader1.gif "+"/></br</br>
you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")
You should console.log(data) to check if the data value has any problem.
use try/catch to catch message if error happened in JSON.parse.
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>
I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>
i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}

Server side URL returns empty response

I have a php file that returns a result that is JSON encoded. Im using:
$.GET("thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
"thephpfile.php" is in the same folder as the javascript page. Currently, I get a blank page. But when I add full path it works like this:
$.GET("http://locahost/thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
How do I fix this issue?
Please use following code for the solutions.
<?php
define("ROOT_WWW","http://".$_SERVER['HTTP_HOST'] ."/yourprojectname/");
?>
<script type="text/javascript">
var ajax_folder="<?= ROOT_WWW ?>";
</script>
$.GET(ajax_folder+"thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});
$.GET("/thephpfile.php",function(data){
ipaddress = data['ip_address'];
document.write(ipaddress)
});

Invalid XML format - How to avoid this

I'm getting data from a database in PHP/mysql, which has invalid characters, such as &. I'm creating the XML as follows:
$stmt->bind_result($foo)|| fail('An error occurred: MySQL bind_result', $db->error);
$foo=htmlspecialchars($foo, ENT_XML1, 'UTF-8');
$xmlstr = "<?xml version="1.0" encoding="UTF-8" standalone="yes">
<xml>";
while ($stmt->fetch())
{ $xmlstr.="
<RECORD>
<FOO>$foo</FOO>
</RECORD>";}
$xmlstr.="
</xml>";
$stmt->close();
echo $xmlstr;
I'm trying to receive the data and put in an array with javascript - but it gives me the error Invalid XML format. I'm receiving random records and sometimes it does work. So it seems to me that the issue is in the characters coming from the database.
The error occurs here in JavaScript:
var foo;
var formData = "label="+label; //Name value Pair
$.ajax({
url: './php/foo.php',
type: 'POST',
data : formData,
dataType: 'xml',
success: function(returnedXMLResponse){
$('RECORD', returnedXMLResponse).each(function(){
foo = $('FOO', this).text();
})
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
You could use an XMLWriter to ensure correct encoding and such.
<?php
$stmt = new Dummy;
$stmt->bind_result($foo);
$xml = new XMLWriter();
$xml->openURI('php://output');
$xml->setIndent(true);
$xml->startDocument();
$xml->startElement("xml");
while ( $stmt->fetch() ) {
$xml->startElement("RECORD");
$xml->writeElement('FOO', $foo);
$xml->endElement(); // RECORD
}
$xml->endElement(); // xml
class Dummy {
public function bind_result(&$var) {
$this->var = &$var;
}
public function fetch() {
static $arr = array('Barnes & Noble', 'Barnum & Bailey', "Buy'n'Large");
if ( current($arr) ) {
$this->var = current($arr);
next($arr);
return true;
}
return false;
}
}
The characters you're getting from the database are not invalid. <, >, & and such are perfectly legal text and can be included in an XML document. However because they have special meaning to an XML parser they need to be escaped. That is:
& --> &
> --> >
< --> <
By far the easiest way to do this is not to build the XML by string concatenation as your code sample attempts to do. Instead use a library that automatically escapes characters as necessary as the document is constructed. XMLWriter has already been suggested. DOM is another option.
I got rid of the parse error by adding a header:
header('Content-type: text/xml');
$xml = new XMLWriter('UTF-8', '1.0');
$xml->openURI('php://output');
$xml->setIndent(true);
$xml->startDocument();
$xml->startElement("XML");
while ( $stmt->fetch() ) {
$xml->startElement("ITEM");
$xml->writeElement('ELEMENT', $reviewdate);
$xml->endElement(); // </ITEM>
}
$stmt->close();
$xml->endElement(); // xml
$xml->flush();
unset($xml);
I would start by looking in the browsers network traffic and analyzing the xhr response body to see what your browser is getting as far as the xml payload (data). You can do this in Chrome or IE using F12 developer tools, or if you want to catch it using another proxy, take a look at Fiddler:
http://www.telerik.com/fiddler
Hope this helps!

PHP not receiving POST body set in Polymer core-ajax element

I've created a Polymer element using core-ajax to send data via POST to a PHP script.
<polymer-element name="login-process">
<template>
<core-ajax auto method="POST" id="login" url="/login.php" response="{{response}}">
</core-ajax>
<button on-tap={{doSend}}>send</button>
</template>
<script>
Polymer('login-process', {
ready: function() {
},
doSend: function() {
this.$.login.body = '{"foo": 1, "bar": 2}';
this.$.login.go();
},
responseChanged: function(oldValue) {
console.log(oldValue);
console.log(this.response);
}
})
</script>
</polymer-element>
I've examined the HTTP request, and verified the data is being sent. However, my PHP script - on the other hand - is not showing traces of the data in the $_POST or $_REQUEST variables. This is the contents of my PHP script:
header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
header("Pragma: no-cache"); //HTTP 1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
error_reporting(E_ALL);
ini_set("display_errors", 1);
define("BASE_PATH", $_SERVER['DOCUMENT_ROOT']);
define('WP_USE_THEMES', false);
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . '/wp-load.php');
var_dump($_POST);
var_dump($_REQUEST);
$creds = array();
$creds['user_login'] = 'example';
$creds['user_password'] = 'plaintextpw';
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ) {
header("HTTP/1.0 401 Unauthorized");
echo $user->get_error_message();
exit();
}
header("HTTP/1.0 200 OK");
exit();
Not elegant code, I know. But the response I get from the script is:
array(0) { } array(0) { } ERROR: Invalid username. Lost
your password?
So the $_POST and $_REQUEST arrays are empty, when I'm expecting them to be filled with the data I've provided.
in this case you would want to use the "params" attribute this.$.login.params = '{"foo": 1, "bar": 2}'; in place of the "body" attribute. doing so would allow you to get the data with $_POST. the following plunker i used for another answer showing how i create a form in polymer but will also work here to show sending $_POST data to a backend with php. http://plnkr.co/edit/JG7KKbMK0R1Fa1W2Gb4P?p=preview
Here is how I'm using core-ajax to POST some data:
in the template:
<core-ajax
method="POST"
id="core_ajax_el"
on-core-response="{{ajax_get_responseHandler}}"
>
</core-ajax>
in the prototype:
domReady: function(e) {
//set AJAX request params: they will be POSTed to the ajax-url.
var core_ajax_el = this.$.core_ajax_el;
// create the object literal
var aniArgs = {};
aniArgs['post_data'] = this.element_attribute;
core_ajax_el.params = aniArgs;
//set the AJAX URL
core_ajax_el.url = this.ajax_get_url;
//execute AJAX
core_ajax_el.go();
},
ajax_get_responseHandler: function(e, detail, sender) {
//do something with the response here
}
So I did some research and made some important findings.
core-ajax has a property contentType which is by default set to 'application/x-www-form-urlencoded'.
The data I was sending was a json object, and it was not url-encoded.
PHP populates $_POST and $_REQUEST when it contains url-encoded data.
Further, the data must be in the form of key=value[&key=value...] pairs, as with GET query variables, for the PHP assoc array indices to be instantiated.
So I could have sent the data with the following code:
this.$.login.body = 'data='+encodeURIComponent(JSON.stringify({"foo":1, "bar":2}));
now in the PHP script:
echo $_POST['data']; // outputs something like string(32) "{\"foo\":1, \"bar\":2}"
var $unescaped = stripslashes($_POST['data']);
echo $unescaped; // outputs string(29) "{"foo":1, "bar":2}"
$assoc_array = json_decode($unescaped, true); // now contains an assoc array of the
// json data
However, I've seen people use the following code in their PHP script:
file_get_contents("php://input");
This gets raw POST data sent to the web server, regardless of whether or not it is url-encoded.
So, I can just as easily continue sending the data with:
this.$.login.body = '{"foo": 1, "bar": 2}';
and with PHP have the data set using:
$data = json_decode( file_get_contents( "php://input", true ) );
echo $data["foo"]; // outputs 1

Categories