Unable to find why base64 image code is invalid - javascript

Can anyone tell me why the base64 image code linked in here is invalid? Some kind of issue with the syntax I believe?
My file looks like this:
/9j/4AAQSkZJR..........39b/lRk5HGVz8
I have truncated it (the "...") since the entirety of the file won't fit in the question.
Here is my Javascript Fetch API POST code:
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
//console.log("base64: "+b64data);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};

Yes I believe the syntax is not correct and it may not be a valid image or some parts are removed.
check this link https://jsfiddle.net/casiano/xadvz/
<img src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+Wltd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Jx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==">
the format should likely began with this: data:image/gif;base64, or just this image/gif;base64, so first section shows image type. in your case it should be image/jpeg and the ;base64, is like defining that its a base64 inline image.
And at the end of the code or just end of anybase64 coded content there should be like == or = but you should not remove it its part of the coded content.

So this is another answer. I post it separately, cause your question is changed.
There is two way to achieve this. First is to use URL-encode and URL-decode. So before you send the base64 string containing your image data u do encode it then on the server side you first echo is to see how it looks. Then you use PHP urldecode to get your string back.
URL decode/encode with javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
URL decode/encode in PHP:
http://php.net/manual/en/function.urlencode.php
https://stackoverflow.com/a/4744917/9453736
But the other way which should fit better in this situation is to use the post body when u wanna post something. But as you are already using a library to do that I guess its just the limitation of your library. So try to check if there are other ways to set parameters for POST with that library. Like you are adding the parameters to body but the way you do it (the library) just limits you. so for example you cant use some characters when you do this:
{
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
{
So in case you failed to find other ways to do the request. Like you can do it with form object with pure javascript and other ways. so in case you failed just go with the first one try to url encode the data.
example of url encode in javascript:
// encodes characters such as ?,=,/,&,:
console.log(encodeURIComponent('?x=шеллы'));
// expected output: "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
console.log(encodeURIComponent('?x=test'));
// expected output: "%3Fx%3Dtest"
example of urldecode in PHP:
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("La valeur du paramètre \"%s\" est \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
}
}

Related

How to change : Fullcalendar generates GET request

I am implementing fullcalendar on my website.
I have created a div with calendar as id.
I have put data from a SQL query in a php variable and used json encode to get the right format.
This is how I create the calendar :
$html .= "<script src='/wp-content/plugins/biobelt/moment.min.js'></script>
<script src='/wp-content/plugins/biobelt/fullcalendar.min.js'></script>
<link rel= 'stylesheet' href='/wp-content/plugins/biobelt/fullcalendar.css' type='text/css'>
<script>
jQuery(document).ready(function() {
var bevents = '".$buildingevents."'
console.log(bevents)
jQuery('#calendar').fullCalendar({
defaultDate: '" . $_SESSION['statDateFrom'] ."',
editable: true,
events: bevents,
});
});
</script>";
The console log gives me an output of the array that I am passing to events, and it is the correct format :
[{"id":"1","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"2","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"3","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"},{"id":"4","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"}, etc...
What I get from this is :
GET 403 Forbidden Error
I checked in apache logs, this is because the URL is too long since every field of the array is put into the url.
For some reason I don't want to change the limit request line in apache conf file.
I want to generate a POST instead of GET request.
And I would like to know how it generates a GET request since I didn't put GET anywhere in my files.
EDIT :
according to : https://fullcalendar.io/docs/events-json-feed
Fullcalendar create the get request and the URL. The problem persists since the URL is too long and I want to create a POST request instead. How to do that?
You seem to have misunderstood the documentation somewhat.
You said
The console log gives me an output of the array that I am passing to events, and it is the correct format
And indeed what you've showed does look like a Javascript array. So...it's a static array and not a URL. You do not have any kind of server endpoint to which you can make a separate ajax call to get your events. Therefore the article you linked to (https://fullcalendar.io/docs/events-json-feed) is not relevant. Instead you are providing a static list of events as per the method described at https://fullcalendar.io/docs/events-array).
Except that...you're not. Due to the way you've written your code, you're providing a string instead of an array. That is causing fullCalendar to assume you're providing a URL, and then trying to call that URL, and it's no surprise that it errors.
If you simply remove the single quotes from
var bevents = '".$buildingevents."'
so that it becomes
var bevents = ".$buildingevents.";
then your code should work ok, because this will inject a hard-coded array into the JavaScript instead of a string.

PHP $_GET and underlines

I have a very short piece of PHP that I use to make HTTP requests from JavaScript.
<?php echo file_get_contents($_GET['url']); ?>
I have used it successfully in a few projects, but am running into a problem with making requests in my current project. Based on my searching, I believe it may be caused by the underscore in the request, though through my searching and not knowing PHP, I have not been able to confirm that.
Below is an example of what I am doing from JavaScript:
$.get("grabber.php?url=" + "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
If I copy the url and put in it in a browser, I get back the JSON that I requested. When I use the code above, I end up getting an error message from NOAA:
Wrong Product : Product cannot be null or empty Wrong Time zone: Time zone cannot be null or empty Wrong Unit:Unit cannot be null or empty Wrong Format: Format cannot be null or empty Wrong Date: The beginDate cannot be null or empty
Do I need to use a regex for the underscore in PHP? Is there some other issue that I do not understand?
Thanks.
You need to send it encoded, which will convert all the underscores/spaces/ampersands etc. with their encoded equivalents:
var url = "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW";
$.get("grabber.php?url=" + encodeURIComponent(url), function(forecast){
console.log(forecast);
}
Using encodeURIComponent() on that URL shows:
http%3A%2F%2Ftidesandcurrents.noaa.gov%2Fapi%2Fdatagetter%3Fstation%3D8573364%26begin_date%3D20160202%26end_date%3D20160203%26product%3Dpredictions%26units%3Denglish%26time_zone%3Dgmt%26format%3Djson%26application%3Dposeidonweathercom%2B%26datum%3DMLLW
Alternatively, if you just want to access the JSON data and handle it within the JavaScript function, you can retrieve the data via the URL directly, without having to encode the URL:
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
Um why do you even need your php code ... the code below will work just fine and eliminate your server overhead.
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});

How do I URL Encode a URL parameter that is itself a URL?

Quick background -
I am making a jQuery ajax call to a service I wrote that returns a JSON response. The service accepts a web site URL (i.e. www.google.com, www.xyz.com/abc123). The format of the request is as follows:
http://www.mysite.com/[url]
... where [url] is a user provided URL (again, something like www.google.com/abc)
I need to URL encode the parameter, as mysite.com/www.google.com is giving me errors.
My problem is, all of the standard javascript encoding functionality does not actually encode the URL.
An example:
<html>
<head>
<script>
document.write("encodeURIComponent = " + encodeURIComponent("www.google.com") + "<br />");
document.write("encodeURI = " + encodeURI("www.google.com") + "<br />");
document.write("escape = " + escape("www.google.com"));
</script>
</head>
<body>
</body>
... has the following output:
encodeURIComponent = www.google.com
encodeURI = www.google.com
escape = www.google.com
What is the proper way to achieve this using JavaScript/jQuery?
I don't think it's relevant, but just in case, this is a Rails 3.0.7 app.
EDIT FOR MORE DETAIL
If www.google.com is already URL encoded, and periods are fine in my URL (www.mysite.com/www.google.com), why am I getting this error?
From Chrome Dev Tools:
GET http://localhost:3000/s/www.google.com 404 (Not Found)
My jQuery snippet:
$.getJSON("http://localhost:3000/s/" + encodeURI($("#txtURL").val()), function(data) {
alert(data.result.url);
});
This is a perfectly valid URL:
http://mysite.com/s/www.google.com
I suspect that you're just running into the Rails format stuff (i.e. .html at the end of the URL sets the format to HTML, .js for JSON, ...) so you just need to fix your route to keep the format auto-detection from getting in the way:
map.connect '/s/:url', :requirements => { :url => /.*/ }, ...
or
match '/s/:url' => 'pancakes#house', :constraints => { :url => /.*/ }, ...
or whatever routing syntax you're using.
If you don't tell rails that the :url should match /.*/ (i.e. anything at all), it will try to interpret the periods in the route as format specifiers, that will fail and Rails will 404 because it can't figure out how to route the URL.
URL encoding escapes characters that have a special meaning in the URL (like / and ?) and/or aren't ASCII characters. http://mysite.com/www.google.com is a perfectly valid URL, there's nothing to escape. If you'd include the protocol as well, you'd get some escape-worthy characters:
encodeURIComponent('http://www.google.com')
"http%3A%2F%2Fwww.google.com"
If your server 404s on a request to http://localhost:3000/s/www.google.com, that means the URL isn't handled by the server. It doesn't mean that the URL is invalid.
As mu said dots don't need to be encoded.
The jQuery-way for building a proper QUERY_STRING would be the use of $.param()
$.param({encodeURIComponent:'http://www.google.de'})

Is there a way to load an Image in Javascript with data retrieved via an HTTP POST?

Is there any means to use AJAX to request an image file via an HTTP POST and then create a new Image with that data in HTML? Since you can't do this with the IMG tag, is it possible to do it with an Image javascript object?
Yes that is possible.
When your serverscript opens the image files and encodes them as a base64 string, almost all browsers (except IE7 and below) can handle that. For instance:
jQuery('<img>', {
src: 'data:image/jpeg;base64,' + someBase64EncodedString
}).appendTo(document.body);
A real-world example of this, can be found here: https://github.com/jAndreas/Supply
You might want to check out how to embed base64 encoded data as an image.
Here's an article that walks you through it.
http://danielmclaren.com/node/90
Try looking here: http://emilsblog.lerch.org/2009/07/javascript-hacks-using-xhr-to-load.html
If it returns the base64 encoded image data you could probably do it using data URIs and possibly Canvas.
Some "pseudo" code (using PHP and JS+jQuery) to demonstrate what you could do.
Server:
$image = new Imagick($imagePath);
echo 'data:image/png;base64,' . base64_encode($image);
Client:
$.ajax({
method: "post",
url: "/foo/bar.php",
success: function (data) {
$("<img />").attr("src", data).appendTo("#myContainer");
}
});

Decode Javascript Encoded Variables

How do I decode encoded javascript variables like:
_0xa2bax2
_0xa2bax3
_0xa2bax5
Edit
I decoded most of it but there are still portions I can't decode:
var _0xa2bax2 = 'DESCRIPTION';
FB['api'](
'/me/feed',
'post',
{ message: _0xa2bax2 },
function (_0xa2bax3) {}
);
From the code sample you provided in your comment (and I edited into your question), those appear to be just arbitrary variable names in the code. Using the code sample from here, they are probably translated roughly into something like this:
_0xa2bax2 = message to post to the wall
_0xa2bax3 = response from the post - can be used to check for error message from posting or retrieve the new Post ID
_0xa2bax5 = no idea?? you don't have any examples...
See the FaceBook Developers API page for more information.

Categories

Resources