PHP $_GET and underlines - javascript

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);
});

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.

Unable to find why base64 image code is invalid

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+8v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O92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+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]));
}
}

The file is emptied when I use file_put_contents

Main issue was solved in comments, although one of the bonus questions is still open and the other's solution could use some improvement
All of this takes place on a webhosting service, the folder structure is as follows:
The JavaScript and PHP files are in /public_html/, the JSON is in /public_html/data/.
In my JS code, I'm sending a POST request with some data for my JSON file:
console.log(objdata.buildings[0].coords);
var params = JSON.stringify(objdata);
if (objdata.buildings[0].coords != " "){
$.ajax({
type: "POST",
data: params,
url: "writecoords.php",
success: function(data){
console.log(params);
console.log(data);
console.log("AJAX success");
},
error: function(){
console.log("failed to send POST");
alert("error");
}
});
}
PHP file:
<?php
function debug_to_console($data){
if(is_array($data) || is_object($data))
{
echo("\n".json_encode($data));
} else {
echo("\n".$data);
}
}
$newJSON = json_decode(file_get_contents('php://input'));
debug_to_console($newJSON);
if (is_writable('data/strogi.json')) {
$a = file_put_contents('data/strogi.json', $newJSON);
if(! $a)
debug_to_console("Wrote nothing");
debug_to_console("PHP write success");
} else {
debug_to_console("PHP write failed");
}
?>
As you can see, I perform a check at every possible point to see if I'm actually processing non-empty data -- I log the value of the key in question, the AJAX request is sent only if it was changed, I log the data being sent and I log the data my PHP file receives and decodes.
I also check if the file is writable to avoid a possible permission problem, and only then I try to write to the file. The file comes out empty and I get the following outputs in console
params is my JSON object as a single line;
data is: my JSON object as a single line with line breaks before every new object and all cyrillic converted to \u format, "Wrote nothing!", "PHP write success";
"AJAX success"
If I check the strogi.json file after this, it's absolutely empty.
To rule out a problem with the format of passed JSON object, I tried writing to a simple test.txt file in the same directory as the .php, which turns out empty as well.
I tried using the method described here, but nothing changed.
I tried using a FTP upload (the method is pointed out somewhere in the comments here), and I got "No such file or directory" returned both for the strogi.json and test.txt files. I used both public_html/test.txt and test.txt as file name.
I tried using the combination of locks FILE_APPEND | LOCK_EX, and no changes happen to either of the files.
My questions are:
Why?
Can a different solution be used if all of this is taking place in the .done() callback for $.getJSON() called on the same file?
Follow-up question worthy of a separate section:
coords is a 3-dimensional array
[
[[x1,y1],[x2,y2],...]]
]
where the external array contains up to two arrays. The first array contains points of the external polygon and (if present) second array contains points of the internal polygon that serves as a cutout.
The code in question is an attempt to make submitting the coords array to strogi.json work for at least one object.
What I'm trying to do, in general, is
$.getJSON() the data/strogi.json file
go through the buildings[] array of objects inside it in the .done()
callback
for each object, check if "coords" is " " (default value)
If it is, a constructor is called to build a polygon using a map API, and when construction is finished, $.ajax is used to submit coords extracted through one of API's functions.
As of now, I'm submitting the whole JSON object, because I'm only working with one of the inner objects, but I imagine resubmitting the whole thing is excessive with multiple objects presented.
Is there a way to pass objdata.buildings[i].coords with the index i to PHP to change the "coords" key value in JSON for a certain buildings[i] object?
Do I need to make any changes to the way I'm processing data to make my JSON valid upon further reads? I assume I'd have to change the "coords" value from [[[x1,y1],[x2,y2]]] (the way it's passed now) to something like this (pastebin because there's no code formatting even though I'm using the 4 space indent)
for it to work, right? How do I do that? partly solved by going through the array in JS with two for() loops and applying toString() to every coordinate, there's gotta be a better way

PHP file called by javascript and another php file

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources