I have an URL that javascript reads from an user input.
Here is a part of javascript code:
document.getElementById("Snd_Cont_AddrLnk_BG").value=encodeURI(document.getElementById("Con_AddresWeb_BG").value.toString());
Then I post the value of the string through CGI to a Perl Script (here is a part of perl code):
#!/usr/bin/perl -w
##
##
use strict;
use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use URI::Escape;
my $C_AddrLnk_BG=$query->param("Snd_Cont_AddrLnk_BG");
my $lst_upload_dir="../data";
my $lst_file_bg=$lst_upload_dir."/contacts_bg.js";
open(JSBG,">$lst_file_bg") || die "Failed to open $lst_file_bg\n";
printf JSBG "var GMapLink_bg=\"".uri_unescape($C_AddrLnk_BG)."\";\n";
close JSBG;
system("chmod 777 $lst_file_bg");
Somewhere in uri_unescape a problem occurs:
The original string from input is:
https://www.google.bg/maps/place/42%C2%B044'15.0%22N+23%C2%B019'04.2%22E/#42.7368454,23.317962,16z/data=!4m2!3m1!1s0x0:0x0
The string after javascript encodeURI() is:
https://www.google.bg/maps/place/42%25C2%25B044'15.0%2522N+23%25C2%25B019'04.2%2522E/#42.7368454,23.317962,16z/data=!4m2!3m1!1s0x0:0x0
And the script after perl uri_unescape() that is printed in file is:
https://www.google.bg/maps/place/42%C2%B044'15.0%22N+23%C2%B019'04.2 0.000000E+00/#42.7368454,23.317962,16z/data=!4m2!3m1!1s0x0:0x0
I can not ascertain whether the problem is in unescaping or printing, but the part
%2522E
is interpreted as
0.000000E+00
(with 10 leading spaces).
Can anyone help me with an idea of what I was doing wrong?
There are numerous problems with your code.
document.getElementById("Snd_Cont_AddrLnk_BG").value =
encodeURI(document.getElementById("Con_AddresWeb_BG").value.toString());
I can't figure out when you think encodeURI here. All you should have is the following:
document.getElementById("Snd_Cont_AddrLnk_BG").value =
document.getElementById("Con_AddresWeb_BG").value;
printf JSBG "var GMapLink_bg=\"".uri_unescape($C_AddrLnk_BG)."\";\n";
Now the erroneous encodeURI is removed, uri_unescape needs to be removed too.
Furthermore, adding quotes around text doesn't always make it a valid JavaScript literal. The easiest way to do that is as follows:
use JSON qw( );
my $json = JSON->new()->allow_nonref();
$json->encode($C_AddrLnk_BG)
That snippet also misuses printf. printf takes a format parameter, so you want
printf FH "%s", ...
or simply
print FH ...
So what you end up with is:
use JSON qw( );
my $json = JSON->new()->allow_nonref();
$json->encode($C_AddrLnk_BG)
print JSBG "var GMapLink_bg=" . $json->encode($C_AddrLnk_BG) ."\n";
You are using printf instead of print to output the result of uri_unescape. It is interpreting %22E as an engineering-format floating point field with a width of 22. Presumable you have nothing else in the printf parameter list, so undef is being evaluated as zero, resulting in 0.000000E+00.
If you had use warnings in place as you should, you would see messages like Missing argument in printf
Related
could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual
So, I have a HTML which is written into a perl string. This html represents a template and I need to add fields on runtime.
For example:
$templateHTML.= '<span > %{name} </span>
I want to replace the %{name} with the required value.
The regex I have tried is:
$htmlTemplate.=~ s/%{name}/akhil;
This didn't work, also is there a way I can use JavaScript's replace function, i.e, can I convert the perl string to js string and process it?
On request, the template is invoked and the values to be added are passed as parameters.
This solved:
my $find = "%{name}";
my $replace = "had";
$find = quotemeta $find; # escape regex metachars if present
$str =~ s/$find/$replace/g;
Source : http://www.perlmonks.org/?node_id=98357
Giving the values directly, didn't work. I am not sure why, will look up and get back.
You're inventing your own templating system. And it seems unlikely that you'll invent something as flexible or powerful as the ones we already have. So I'd recommend you use something like the Template Toolkit instead.
But if you want to continue with your plan, you should read the relevant section from the FAQ.
How can I expand variables in text strings?
(contributed by brian d foy)
If you can avoid it, don't, or if you can use a templating system, such as Text::Template or Template Toolkit, do that instead. You might even be able to get the job done with sprintf or printf:
my $string = sprintf 'Say hello to %s and %s', $foo, $bar;
However, for the one-off simple case where I don't want to pull out a full templating system, I'll use a string that has two Perl scalar variables in it. In this example, I want to expand $foo and $bar to their variable's values:
my $foo = 'Fred';
my $bar = 'Barney';
$string = 'Say hello to $foo and $bar';
One way I can do this involves the substitution operator and a double /e flag. The first /e evaluates $1 on the replacement side and turns it into $foo. The second /e starts with $foo and replaces it with its value. $foo, then, turns into 'Fred', and that's finally what's left in the string:
$string =~ s/(\$\w+)/$1/eeg; # 'Say hello to Fred and Barney'
The /e will also silently ignore violations of strict, replacing undefined variable names with the empty string. Since I'm using the /e flag (twice even!), I have all of the same security problems I have with eval in its string form. If there's something odd in $foo, perhaps something like #{[ system "rm -rf /" ]}, then I could get myself in trouble.
To get around the security problem, I could also pull the values from a hash instead of evaluating variable names. Using a single /e, I can check the hash to ensure the value exists, and if it doesn't, I can replace the missing value with a marker, in this case ??? to signal that I missed something:
my $string = 'This has $foo and $bar';
my %Replacements = (
foo => 'Fred',
);
# $string =~ s/\$(\w+)/$Replacements{$1}/g;
$string =~ s/\$(\w+)/
exists $Replacements{$1} ? $Replacements{$1} : '???'
/eg;
print $string;
I am using an API which encodes some part of the content using JavaScript. That content is visible in the browser, but while I access it using curl in PHP I get plain JavaScript code as there is no JS engine on server. I would like to decode/unescape Unicode characters in PHP, as JavaScript does. Is that possible?
Please find a snippet of plain JavaScript I get as a response below:
eval(unescape("document.write('%u0039%u0032%u0039%u0032%u0034')"));
The snippet code should return 92924
Ok, I found a solution to that problem.
I am now parsing out the content string and then use json_decode function to unescape Unicode characters, but first %u has to be replaced with \u. Here is my code:
$string = "%u0039%u0032%u0039%u0032%u0034";
$unescaped = str_replace("%u","\u", $string);
echo json_decode('"'.$unescaped .'"');
This code would output: 92924
This is an oddball question, but I have been working on this for hours now and am not making much progress. I am hoping someone here may be able to advise...
I am porting a script from php to node. The php script makes use of this function:
hash_hmac('sha512', $text, $key);
I have reproduced this in node using the crypto module:
var hash = crypto.createHmac( "sha512", key );
hash.update( text );
return hash.digest( "hex" );
I have verified that these functions produce the same hash when given the same text and key.
Except...
The string that is being used for a key in php looks similar to this: (Don't ask)
define("SITE_KEY", "
__
, ,' e`---o
(( ( | ___,'
\\~-------------------------------' \_;/
( /
/) ._______________________________. )
(( ( (( (
``-' ``-'
");
I have tried to reproduce this in Javascript like so:
var key = "\
__\
, ,' e`---o\
(( ( | ___,'\
\\\\~-------------------------------' \\_;/\
( /\
/) ._______________________________. )\
(( ( (( ( \
``-' ``-'\
\
";
But it doesn't work. (I assume it has to have something to do with the linebreaks).
Replacing the newlines with "\r\n" or "\n" as in the following also does not work:
var key = "\r\n __\r\n , ,' e`---o\r\n (( ( | ___,'\r\n \\\\~-------------------------------' \\_;/\r\n ( /\r\n /) ._______________________________. )\r\n (( ( (( ( \r\n ``-' ``-'\r\n\r\n";
Suggestions on how to fix this? (Getting rid of the dog is not an option, unfortunately.)
Thanks (in advance) for your help.
Why not store the string BASE64 encoded? That way you don't need to worry about line breaks, whitespace, anything like that.
Seeing as your php code is storing the key (apparently) correctly, try a script like:
<?
$doggy_key = ....;
echo base64_encode($doggy_key);
Run it from the command-line, copy the encoded key, then use it in your javascript.
Decoding base64 strings is a simple problem, for example;
Base64 encoding and decoding in client-side Javascript
There are no line breaks in the original string, to my knowledge. The backslash at the end tells PHP that the next line is just a continuation of the previous. To test whether I'm right or not, you could get PHP to print out the string and see if it has line breaks in it. But I suspect that you can write this in one long, or joined, string in Javascript.
Try replacing all of the newlines in the PHP version with \n (and no newline) in the JS version. If that doesn't work, try replacing them all with \r\n — I bet PHP doesn't translate multiline literals in windows-formatted source :)
I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { "var": "value", ... }). However, if any of the values contains a single quote (properly escaped like \'), jQuery fails to parse an otherwise valid JSON string. Here’s an example of what I mean (done in Chrome’s console):
data = "{ \"status\": \"success\", \"newHtml\": \"Hello \\\'x\" }";
eval("x = " + data); // { newHtml: "Hello 'x", status: "success" }
$.parseJSON(data); // Invalid JSON: { "status": "success", "newHtml": "Hello \'x" }
Is this normal? Is there no way to properly pass a single quote via JSON?
According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:
Update - More information for those that are interested:
Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:
JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.
So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.
Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:
The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:
...
Strings may be quoted with ' (single quote).
This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:
public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {
...
case '\\':
c = this.next();
switch (c) {
...
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...
At the top of the method is an informative comment:
The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.
So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.
Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:
parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
jQuery.error( "Invalid JSON: " + data );
},
As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.
If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027 see http://www.utf8-chartable.de/ for all of them
edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
When You are sending a single quote in a query
empid = " T'via"
empid =escape(empid)
When You get the value including a single quote
var xxx = request.QueryString("empid")
xxx= unscape(xxx)
If you want to search/ insert the value which includes a single quote in a query
xxx=Replace(empid,"'","''")
Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.
What I finally end up doing was replacing the single quote ' with it code ' using a regex after the stringify() method call the following way:
var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "'");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.
Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?
The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.