PHP Unserialize Javascript serialized string - javascript

Good day,
I got a new script (for me it is) that allows you to create a draggable tree view.
The order of the tree structure can be changed and also stored.
I managed to send and fetch the updated structure.
However I have not yet succeeded in unserializing the string.
Before I am going to write my own logic to decode the array I would like to know if PHP knows some functionality by default to solve this issue?
Example
The String that I have :
spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null
The code that generates this string :
serialized[0].hash
I hope anyone could tell me what I have done wrong. OR IF this even a usable structure.
Thanks in advance
Note
The results are bing written by PHP to a file called test.txt
When I try to get the results I try it like this:
<?php
$cont = file_get_contents('test.txt');
$Str = parse_str($cont);
echo '->'.$Str.'<-';
?>
This produces : ><
Hence an empty string.
The following is a working solution:
<?php
$cont = file_get_contents('test.txt');
parse_str($cont, $Str);
echo print_r($Str);
?>
(* the array that comes out of it is pretty useless actually *) but THANKS

This is all you need:
$arr = [];
$string = "spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null";
parse_str($string, $arr);
var_dump($arr);
Source: http://php.net/manual/en/function.parse-str.php

Related

Passing PHP array to Javascript w/o showing up in source

I'm working on a historical database with 2,000+ photos that need to be categorized of which about 250 are loaded. I've created a MYSQL database with 26 fields to hold this data.
I'm using PHP to access the database and retrieve the information.
I'd like to use JavaScript to manage the rest of the form. All of the code is in one php file.
The problem I'm running into is when I
//$result is the php associative array holding the photo information
<div id="dom-target" style="display: none;">
<?php echo json_encode($result); ?>
</div>
<script>
var div =document.getElementById("dom-target");
var photo_array = JSON.parse(div.textContent);
It works but, I get the entire database structure and data embedded in the source html output. Obviously this won't do especially as the photo count increases.
How can I prevent this?
If I were to split this one php file into two, one containing php accessing the database and returning an array, and the other page containing all of the input boxes etc., and use AJAX passing the array as a JSON; would that work? I'd hate to go down that path unless it'll be successful. I've read where you can't pass the array if all of the code is on one page.
Or, should I just stick with doing everything in php?
Thanks, Eric
Edit: What I want to do is to pass a php array to js without having all of the data in the array included in the source. By source I mean when someone "views source". I also think that once I get up to 2,000 photos is is going to be unwieldy....(2,000 photos) x (26 fields) = a lot of stuff needlessly included in the web page.
I have no objection to using AJAX. But all of the examples I've seen have the request on one page and the response on another. Do I need to split up my code onto two pages; one to handle the php and MySQL and the other to handle the html and js?
What I envision is a screen showing the selected photo at 800x600 with the input fields below that. A person enters the title, caption, description etc and that is saved in the db with the photo's name. Below that I would have 20 thumbnail photos which a person could pick from to enter that photo's information. I would loop through the database 20 or so, photos at a time. Only the file names are stored in the database, the actual photo jpg is stored on a hard disk and retrieved via an statement.
How can I do this without all of the data in the database array being on the html source page?
Edit 2: I've been asked to include more of my php. Sorry I couldn't make it neater.
<?php
$stmt_select->bind_result(
$select_array['fhs_pkey'],
$select_array['file_name'],
$select_array['caption'],
$select_array'post'],
$select_array['photo_type'],
$select_array['last_name'],
$select_array['first_name'],
$select_array['middle_name'],
$select_array['honorific'],
etc., etc., etc
);
// put all of the database info into an array. Filename field is for full size photos
$j=$stmt_select->num_rows;
for ($i=0;$i<$j;$i++)
{
$stmt_select->data_seek($i);
$row = $stmt_select->fetch();
//put all of the column data into the array
foreach ($select_array as $key=>$value)
$result[$i][$key]=$value;
//in a separate php file resize the photos and save them
//put full path with appended filename to retrieve later
$result[$i]['resized'] =
"../images/fhs_images/800x600_photos/800x600--" .
$result[$i]['file_name'] ;
$result[$i]['thumb'] = "../images/fhs_images/200x150_photos/200x150--" .
$result[$i]['file_name'] ;
}
$stmt_select->close();
$stmt_update->close();
$stmt = null;
$conn = null;
echo '<figure id="photo_figure">';
$filename = $result[2]['resized'];
echo "<img src = "."'".$filename."'" ."/>";
?>
<script>
//below is where I get the entire array printed out when I view source
var photo_array = <?php echo json_encode($result); ?>
var testing = photo_array[40]['thumb'];
//take care of spaces in filenames
testing = encodeURI(testing)
document.write('<img src=' + testing + '>')
</script>
Edit 3 #trincot
Something's not right. I moved all of my MYSQL db setup and retrieve into a new file called fhs_get_photos.php. In my jQuery ready function I added the below. See my comments on what gets displayed
var myarray;
$(document).ready(function()
{
$('.tooltips').powerTip();
$(".radio1").on('click',(function()
{
var photo_type = $("input[name='photo_type']:radio:checked").val();
if(photo_type == 2)
$(".person").hide();
else
$(".person").show();
}));
$.getJSON("fhs_get_photos.php", function(photo_array)
{
if (photo_array.jsonError !== undefined)
{
alert('An error occurred: ' + photo_array.error);
return;
}
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
//$.each(photo_array, function(i, obj){
// $("#dom-target").append(obj.fhs_pkey + " " + obj.file_name + ", ");
//this displays correctly on a screen but not with anything else.
//Seems as if it's rewriting the page and only this is displaying which
//may be how it's supposed to go
document.write("In js. photo_array 2,caption is: " + photo_array[2] ['caption']);
});
});
In my main php I put
document.write("photo_array 2,caption is: " + photo_array[2]['caption']);
but it's not displaying anything. I suspect photo_array is not being passed into the page. In the js file, I then created a global variable 'myarray' and in the .getJason function I added
myarray = photo_array;
thinking it would pass into the main file but it didn't.
There are in principle two ways you can think of to get data in JavaScript:
1. Ajax request
With this solution use your current PHP file for generating the HTML page only, so without generating JSON, and create another PHP file which will generate the JSON only.
So let's say your JSON-generating PHP file is called fhs_get_photos.php, then it would have this code (no HTML!):
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
echo json_encode($result);
?>
See the last section in my answer for treating JSON encoding errors.
Make sure there are no line breaks or spaces before the opening <?php, and that you do not echo or print anything else than that one JSON string.
Your database query would also be in this new file. Note that currently you have a mix, like with this line:
echo "<img src = "."'".$filename."'" ."/>";
This line belongs in the non-JSON file, but it also depends on the query. So either you make an include file that does the query, include it in both PHP files, or you move the logic of defining the image tag (or at least the image's source) to the JavaScript part (better!).
Then in the original PHP file, remove the JSON output, and add some JavaScript, using jQuery (I understood you were already using it, so you have it included):
$(function(){
$.getJSON("fhs_get_photos.php", function(photo_array){
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
$.each(photo_array, function(i, obj){
$("#dom-target").append(obj['fhs_pkey'] + " " + obj['file_name'] + ", ");
});
// or things like:
$("#caption_input").val(photo_array[2]['caption']);
});
});
This function will get executed once the HTML DOM has been built, so evidently after the first PHP file has finished execution. It will make the request to the second PHP file. Once that request is answered by PHP, the inner call-back function will receive the data. Note that there is no need to decode JSON here, as jQuery has already done that for you.
2. Generate JavaScript with data
Here you keep your current PHP file, but move the part where you inject the JSON encoded data to the JavaScript block:
<script>
var photo_array = <?php echo json_encode($result); ?>;
// ... process it
</script>
There is no need to wrap JSON in a JavaScript string to then parse it.
From json.org:
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
2.1. Valid JSON that could be invalid JavaScript?
Although not a problem in the context of this question (see below), there is an incompatibility between JSON and JavaScript syntax. It concerns whether or not the non-ASCII characters U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed to appear unescaped in quoted strings:
JSON syntax allows this, as stated in the ECMAScript® 2015 Language Specification, section 24.3.1:
JSON allows Unicode code points U+2028 and U+2029 to directly appear in String literals without using an escape sequence.
JavaScript syntax does not allow this, as indicated in the ECMAScript® 2015 Language Specification, section 11.8.4:
All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence.
PHP's json_encode however, follows the possibility offered in that last line, and escapes all non-ASCII characters, including the problematic U+2028 and U+2028, except if you explicitly tell PHP not to do so with the JSON_UNESCAPED_UNICODE flag:
JSON_UNESCAPED_UNICODE (integer)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.
So, a json_encode call without this flag will not produce instances of this problem.
3. Catch json_encode failures
According to the manual on json_encode the method can return a non-string (false):
Returns a JSON encoded string on success or FALSE on failure.
When this happens echo json_encode($result) will output the empty string, which is invalid JSON.
This error condition should be captured in PHP, for example like this:
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
$json = json_encode($result);
if ($json === false) {
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
}
?>
And then in JavaScript, this condition should be handled as well, for example like this:
if (photo_array.jsonError !== undefined) {
alert('An error occurred: ' + photo_array.jsonError);
return;
}

How to pass multidimensional array from PHP to Javascript?

I am trying to get array value from JSON string, and I do the work with json_decode PHP.
<?php
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
$jsonDecoded=json_decode($jsonContent,true);
foreach($jsonEncoded['BMS'] as $p){
echo '
ID: '.$p['id'].'
Tipe: '.$p['type'].'
';
echo "<br>";
?>
The PHP code works, and give the result of array from JSON string.
And this is my Javascript code
<script>
var bmsdata = <?php echo $jsonDecoded ?>;
alert(bmsdata["1"].id); // For check, i want to see the id of row 1
</script>
But nothing was shown up.
Am i doing right so far? Or i missing something to pass the value from PHP to Javascript? Any suggestion will be appreciated.
$jsonDecoded is the decoded json.
Please change
var bmsdata = <?php echo $jsonDecoded ?>;
to
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
or use the already exisiting variable $jsonContent:
var bmsdata = <?php echo $jsonContent; ?>;
This one should work, as I lookup JSON at http://megarkarsa.com/gpsjson.php ;)
<script>
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
alert(bmsdata.BMS["1"].id); // For check, i want to see the id of row 1
</script>
You just forgot 'BMS' key ;)
Looks like you're injecting a decoded, PHP-representation of the data into your javascript. You probably (if you want to continue doing it this way) want to echo the encoded version (jsonContent) instead.
Ultimately, you might want to rethink the approach. Fetching the data via ajax is often an easier way to work with it, since you don't need to worry about writing bare javascript via php, which has all sorts of escaping issues to get right.

Generate JSON array

I want to generate a JSON array with PHP, but it doesn't work well.
My PHP array looks like this:
protected $resultArray = array("1.0" => 0, "1.3" => 0);
then I do this:
return json_encode($resultArray);
but then i've got this:
var array = [{"1.0":2,"1.3":1}];
Why is " replaced with "?
quot; is a quote character (") encoded as HMTL. json_encode() does not produce HTML encoded sequences.
Replace return with echo in return json_encode($resultArray); and you'll see this for yourself.
Most probably the returned string is passed further to a function that runs it through htmlspecialchars() or htmlentities() and this is the correct way to work with it if you put it into an HMTL context.
Use a different viewer class if you need to output only the json_encode()-ed string. I don't know TYPO3 but I guess you should use JsonView; pass it $resultArray as-is and it will call json_encode() for you.
I think you may using etended library for example in wamp server I tested this code and it's work fine
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span
style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));
//output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}
Thanks guys for help!
The solution is (only for typo3). To get a properly correct JSON-Array in the view the JS code has to be improved the following way:
var array = {f:format.htmlentitiesDecode(value:chartarray)};

Sending PHP Strings Variables to a Javascript String Variables

Hi I am trying to send a long string of numbers from a file to Javascript. One I get it in Javascript as a string the rest will be easy.
This is the PHP code that grabs the series of numbers. It does grab them properly because it prints it out perfectly if I instruct it to do so.
$data = readfile($dataFile);
This is the Javascript Code:
var data = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;
When ever I run it the variable "data" is set to a random number. I assume it is the the number of characters in the sequence. I am relatively new to PHP and Javascript so a nice and clear explanation would be greatly appreciated. Thanks in advance.
Readfile reads the contents of the file and outputs them. It returns the byte length of the file, so $data is the number of the read bytes. link.
The number that is set in the variable $data is the number of bytes read by readfile. This is because readfile only reads the file and outputs its content to the standard output. To get the actual data in the file and assign it to a viariable, you can use file_get_contents(), like this:
$data = file_get_contents($dataFile);
Then the javascript assignment is good ;)
You need quotes if you want it to be a string in Javascript:
var data = '<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;';

Using and retrieving PHP variables within JSON

I've just started using JSON to throw around information between pages and I simply can't figure this one out.
Basically, I have one page that's using jquery getJSON to get some JSON data from another page. But the PHP variables won't/can't get replaced with the necessary content.
Here's the jquery script (which is working fine I believe)
$.getJSON("./menu-controller.php", { editId: getEditId, getEditInfo: true },function(data) {
console.log(data);
var id = data.itemId;
alert(id);
});
I can get it to work just fine when using this code on the other page
$json = '{ "itemId":"4" }';
echo $json;
HOWEVER, if I use this, then it won't work
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
So my question is, how can I get $menuId to actually replace itself with the number and come back on the other page correctly?
I've tried messing with the quotes and re-arranging the quotes for 4 hours. It either comes up with an error or it doesn't replace $menuId with the actual number.
You should make a PHP array instead and then convert it to JSON.
For instance:
$array = array();
$array['itemId'] = $menuId;
echo json_encode($array);
Note: there is also a json_decode function that takes in a JSON string and converts it into PHP as well. You might find that useful.
FYI, PHP variables are interpolated in double quotes only and not in single quotes. So, you've to do something like this:
$json = "{ \"itemId\":$menuId }";
echo $json;
Please see the demonstration over here: http://codepad.viper-7.com/CDC0oM
In this sample:
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
You have wrapped your JSON string in single quotes. PHP substitutes values in double quotes, so the value is not substituted here, and the vale you echo is
{ "itemId":$menuid } - this is not valid JSON.
You're better off creating a PHP array and using json_encode() to create the SON string:
echo json_encode(array("itemId"=>$menuId));
The problem is that you've enclosed your PHP variable within single (rather than double) quotes, so PHP isn't looking in the string for variables to replace.
So this should work:
$json = "{ \"itemId\": $menuId}";
As well as the json_encode method suggested by Cezary Wojcik (which is going to be a lot more flexible if the data gets more complex!).

Categories