PHP Serialize html content - php

I have a page that retrieves from a mysql db (blob) a serialized base64 encoded array, which is then decoded, unserialized, and displayed.
My problem is, any html that is displayed is as plain text (not as code) and the some of the sensitive characters are escaped. " for example is \". I tried adding a str_replace() and although it did remove the \'s it didn't solve the issue.
Here's the code that displays the info:
$array = unserialize(base64_decode($sArray));
if ($array != ''){
foreach ($array as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
It properly adds the td tags to add to the table, but again, the $value is displayed as plain text.
Thanks in advance for any help!
The array is setup something like this:
FieldTitle1 => link
FieldTitle2 => Random Text
FieldTitle3 => 930809830
Sample sArray data:
YToxMjp7aToxO3M6OToidGVzdE5hbWUxIjtpOjI7czozMjoiPGEgaHJlZj1cXFwiI1xcXCI+dGVzdFZhbHVlMTwvYT4iO2k6MztzOjk6InRlc3ROYW1lMiI7aTo0O3M6MTc6IjxiPnRlc3RWYWx1ZTI8L2I+IjtpOjU7czo5OiJ0ZXN0TmFtZTMiO2k6NjtzOjQzOiI8aW1nIHNyYz1cXFwiaHR0cDovL3BsYWNlaG9sZC5pdC8xMHgxMFxcXCI+IjtpOjc7czo5OiJ0ZXN0TmFtZTQiO2k6ODtzOjEwMToiPGlmcmFtZSBzcmM9XFxcImh0dHA6Ly9jcm93bmZ1cm5pdHVyZW1hLmNvbVxcXCIgd2lkdGg9XFxcIjEwXFxcIiBoZWlnaHQ9XFxcIjEwXFxcIiBzZWFtbGVzcz48L2lmcmFtZT4iO2k6OTtzOjk6InRlc3ROYW1lNSI7aToxMDtzOjEyOiJSZWd1bGFyIFRleHQiO2k6MTE7czo5OiJ0ZXN0TmFtZTYiO2k6MTI7czo5OiIxMjk4MzkzNDciO30=

I changed form serialization to json_encode/decode and that solved the issue!
PHP Serialize Successful, Unserialize Failure
Thanks #Eyal Alsheich for pointing this link out!

Related

Get value from JSON and display it (foreach command) in PHP

Hello I've been trying to solve this by myself for a few hours now, with zero luck. I'm trying to use the foreach command in php to display a decoded value from json.
{
-car_data: {
car_id: "87",
car_cost: "62000",
So let's say I want to display the value of car_id, then below that the value of car_cost.
I need to do this using the foreach command. Please briefly explain the process. I'd greatly appreciate it!
It's not clear exactly what you're asking...
If you have a JSON object and need to do something with it server side it is completely different to if you have a JSON object and want to do something with it on the webpage.
N.B.
Your JSON object is malformed there shouldn't be a - in the names.
JSON Object
Made on the client side will look something like:
var cars = {car_data: {car_id: 87, car_cost: 62000}};
Alternatively, server side, you need to convert it to a PHP readable format:
$cars = json_decode('{"car_data":{"car_id":87,"car_cost":62000}}');
JavaScript - Client Side
for(key in cars.car_data){
console.log(key + " => " + cars.car_data[key]);
}
PHP - Server Side
foreach($cars->car_data as $key => $value){
echo "{$key} => {$value}\n";
}
$decoded = json_decode($json);
foreach($decoded->cars_data as $car){
echo $car->car_cost;
}

Escaping slashes when decoding json php

I have a problem when returning a row from database that has a column type TEXT(in this case, column "details") which contains an array of JSON objects. Example:
{
productid: 1
shopid: 1
title: 'Product 1'
--> details: [{"name":"Brand name","value":"Brand value"},{"name":"Color","value":"blue"}]
. . .
}
Data inserted into database in columns of type TEXT are inserted like addslashes(json_encode($array_or_object)) to safely escape before insert.
When returning data, columns of type TEXT by function json_decode() and returned with no problem. Problem occurs when someone tries using single ' and double quotes " in details. Example:
details: [{"name":"\\\"test123\\\"","value":"\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"}]
Returned value looks like:
"details": [
{
"name": "\\\"test123\\\"",
"value": "\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"
}
],
I have more than one way of storing JSON data in database (as object, array of objects, array of arrays of objects,...), and I need a way to escape these backslashes.
Using stripslashes() on the string before using json_decode() does not work, it breaks the JSON.
Creating a recursive function works, but is not as pretty as I would like it to be. Example:
function decode_json($json) {
if (empty($json)) {
return $json;
}
if (is_string($json)) {
$json = json_decode($json, true);
}
foreach ($json as $key => $value) {
if (is_array($value)) {
$json[$key] = decode_json($value);
continue;
}
$json[$key] = stripslashes($value);
}
return $json;
}
Any help is appreciated.
json_encode already escape your string, you don't need to use addslashes()
Example:
$var = ["value" => "test'\""];
print_r(json_encode($var));
Result:
{"value":"test'\""}
And will be better to use PDO with bind parameters: https://www.php.net/manual/en/pdostatement.bindparam.php
and what exactly is the point of using a database, when storing the raw JSON?
decode first, then escape the values to insert - else you'll also escape all of the JSON delimiters,
which might subsequently cripple the whole input string and render it F.U.B.A.R.
PS: PDOStatement still requires PDO::quote() to escape the input properly.

Posting multiple values from html submit form

I'm trying to use an HTML submit which is populated from an associative array from an SQL database, but I would like to pass multiple values as opposed to the usual 1. I've tried using JSON in the value, with the variables and then decode the JSON later to retrieve the individual variables.
<select name="name">
<?php
foreach($array as $vals){
echo '<option value={"a":".'$vals['1']'.","b":".'$vals['2']'.","c":".'$vals['3']'.","d":".'$vals['4']'."}>Option Name</option>';
}?>
</select>
It works as intended until one of the options has a spacing in the string and then in the HTML page. I end up with a problem where somehow an extra " is inserted in the space, so my browser is showing the value:
{"a":"x" y","b":"xy","c":"xyz","d":"xyzz"}
The problem is the "x" y" which I was hoping to be "x y".
Does anyone have ideas on how I can fix this? Or equally any other methods of achieving the same result?
You need to put quotes around the value attribute so that spaces don't terminate it. Also use htmlentities() to encode other special characters.
Also, don't construct JSON by hand, use json_encode().
foreach ($array as $vals) {
$obj = ["a" => $vals[1], "b" => $vals[2], "c" => $vals[3], "d" => $vals[4]];
$json = htmlentities(json_encode($obj));
echo "<option value='$json'>Option Name</option>";
}
I would build the JSON as a PHP array and then you can base64_encode(json_encode()) the array. This would be easier to read and you don't have to worry about other edge cases with this solution.
Check the position of . and '
echo '<option value={"a":".'$vals['1']'.","b":".'$vals['2']'.","c":".'$vals['3']'.","d":".'$vals['4']'."}>Option Name</option>';
Corrected
echo '<option value={"a":"'.$vals['1'].'","b":"'.$vals['2'].'","c":"'.$vals['3'].'","d":"'.$vals['4'].'"}>Option Name</option>';

Looping through json_decode with foreach loop error

I keep running into the error Warning: Invalid argument supplied for foreach() and for the life of me I can't figure out why. Here is my relevant code:
$Ids = $_POST["param-0"];
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
stripslashes($decodedJson);
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
$Ids is a string from a previous file that is encoded with json_encode. I added the stripslashes because it was recommended in another question on Stack Overflow, but it didn't help. If I change the beginning of the foreach loop to beforeach($toReturn as $id) the error goes away. Thanks!
edit: in the previous file, $_POST["param-0"] is an integer array that I returned with json_encode. With the testing data I am working with right now, ["15","18"] is what is being passed.
First you need to decode the json (which you already did)
$decodedJson = json_decode($Ids, True);
Then to grab each value from the json and, for example, echo it. Do this:
foreach ($decodedJson as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
From top to botton:
$Ids = $_POST["param-0"];
This will trigger a notice if input data does not have the exact format you expect. You should test whether the key exists, for instance with isset().
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
This will return null if input data is not valid JSON. You should verify it with e.g. is_null().
stripslashes($decodedJson);
If input data was valid we'll first get a warning:
Warning: stripslashes() expects parameter 1 to be string, array given
Then, if our PHP version is very old we'll have our array cast to a string with the word Array in it, and if our PHP version is recent we'll get null. Whatever, our data is gone.
If input data wasn't valid, we'll get an empty string.
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
Neither null or strings (empty or not) are iterable. There's no nothing to do here. Our data is gone forever :_(
It ended up I was incorrectly encoding what I wanted decoded. All is well again, thanks for everyone's help!

PHP: String to actual value

I am creating a function to parse text from a templating system, and add the corresponding values.
For example, the user might input hi [[first_name]] and the [[first_name]] part will be replaced with the actual first name.
Somehow, I parsed that and ended up with a text that looks like this:
hi $info['first_name']
The above is just as text though, what can I do to actually make $info['first_name'] be the value (I already have that array in there, but I am not sure how to convert string to PHP variable)
Thanks!
Use simple str_replace function:
$str = "hi [[first_name]]";
foreach (array_keys($info) as $key) {
$str = str_replace("[[".$key."]]", $info[$key], $str);
}
echo $str;
str_replace("[[first_name]]", $info['first_name'], 'hi [[first_name]]');
You haven't share your code but you may print the variable name instead of its value.
<?php
$myTemplate = "hi [[first_name]], how are you this fine [[day_of_week]]?";
$myData = array(
'[[first_name]]' => 'James'
,'[[day_of_week]]' => 'Friday'
);
echo str_replace(array_keys($myData), array_values($myData), $myTemplate);
?>

Categories