Can anyone help me with converting the following Python script to PHP?
data = json.dumps({'text': 'Hello world'})
content_sha256 = base64.b64encode(SHA256.new(data).digest())
The value of content_sha256 should be
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=
I have tried to use the base64_encode function, and will only get the desired result if I use the string:
$data_string = "{\"text\": \"Hello world\"}";
base64_encode(hash("sha256", $data_string, true));
but I want to get the desired result by using and array, not a quote-escaped string...
You need to replace python json.dumps with php json_encode
$data_string = json_encode(array('text' => 'Hello world'));
base64_encode(hash("sha256", $data_string, true));
Both of these functions take an associative array and transform it into a string representation. It is then the string that you do a hash/base64 encoding on.
Paul Crovella, you pointed out the correct direction.
I have to do a string replace on the json encoded variable before I send it through the base64, to get the same string as the one made by Python:
$data_array = array("text" => "Hello world");
$data_string_json_encoded = json_encode($data_array);
$data_string_json_encoded_with_space_after_colon = str_replace(":", ": ", $data_string_json_encoded);
$data_string_base64 = base64_encode(hash("sha256", $data_string_json_encoded_with_space_after_colon , true));
Then I get the desired result, the same as in the Python script:
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=
Related
Currently i am facing issue of replace string , I used postman & passing string in postman like [{"id":"115","flag":"1","qty":"3","size":"10"}] as a parameters but when i print string i am getting output like [{\"id\":\"115\",\"flag\":\"1\",\"qty\":\"3\",\"size\":\"10\"}] , So i want to only remove '\' from string i have tried following code but not work.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo $res = preg_replace("/[^a-zA-Z]/", "", $fliesid_in_store);
Have you tried stripslashes.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo stripslashes($fliesid_in_store);
The string you mentioned is in json format
$json = [{"id":"115","flag":"1","qty":"3","size":"10"}] //this is json
Assign that to variable and decode it.
$string = json_decode($json,TRUE) this give result in array format
In your case
$string = json_decode($_REQUEST['fliesid_in_store'],TRUE);
need your help on this one...
I'm trying to create a code that will get a .txt file and convert all text content to json.
here's my sample code:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
I already got the result when i tried to echo the $json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
but when I tried to echo using like this method $json_contents[0]
I only got per character result.
Code
Result
hope you can help me on this one..
thank you
As PHP.net says
"Returns a string containing the JSON representation of the supplied value."
As you are using $json_contents[0] this will return the first char of the json string.
You can do this
$conents_arr[0]
Or convert your json string to PHP array using
$json_array = json_decode($json_contents, true);
echo $json_array[0];
It is happening because $json_contents is a string. It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. You can either decode the encoded json string to object like below:
$json = json_decode($json_contents);
echo $json[0];
or echo it before the json_encode:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
json_encode() function takes an array as input and convert it to json string.
echo $json_contents; just print out the string.
if you want to access it you have to decode the JSON string to array.
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];
How to multilevel base64 decoder and show proper php code....
i.e.....
base64_decode(
base64_decode(
'SkhSb2FYTXRQazh3TUU4d01FOVBUMDh3VDA4Z1BTQm1ZV3h6WlRzZ0NRa2tUekF3VDA4d1R6QXdUMDh3VHlBOUlITjBjblJ2Ykc5M1pYSW9jSEpsWjE5eVpYQnNZV05sS0dKaGMyVTJORjlrWldOdlpHVW9KMGw1T0hWTGFWRnFKeWtzSUNjbkxDQWtYMU5GVWxaRlVsdGlZWE5sTmpSZlpHVmpiMlJsS0NkVk1GWlRWbXRXVTFneFFsTlVNVkpRVVRBNVRTY3BYU2twT3c9PQ=='
)
);
Any buddy have php script to decode multi level base64_decode() and show proper php code.
Note:
Encoded string will be decoded to exact string if the string encoded or decoded equal no. of times.
It means two level encoded string can be decoded 2 level.
<?php
$string="Hello Stack Overflow";
echo $encodedString=base64_encode(base64_encode($string));//Multilevel(2) encode
echo base64_decode(base64_decode($encodedString));//Multilevel(2) decode
I would recommend to create a function similar to this:
function multiBase64Decode($string, int $iteration = 1){
for($i=0;$i<$iteration;$i++){
$string = base64_decode($string);
}
return $string;
}
I have a variable which contains a path in json_encode
/users/crazy_bash/online/test/
but json_encode converts the path to this:
\/users\/crazy_bash\/online\/test\/
Why? How can i display a normal path?
the code
$pl2 = json_encode(array(
'comment' => $nmp3,
'file' => $pmp3
));
echo($pl2);
It's perfectly legal JSON, see http://json.org/. \/ is converted to / when unserializing the string. Why worry about it if the output is unserialized by a proper JSON parser?
If you insist on having \/ in your output, you can use str_replace():
// $data contains: {"url":"http:\/\/example.com\/"}
$data = str_replace("\\/", "/", $data);
echo $data; // {"url":"http://example.com/"}
Note that it's still valid JSON by the definition of a string:
(source: json.org)
Escaped solidus is legal. But if you want a result without escaping, use JSON_UNESCAPED_SLASHESin json_encode option. However, this was added after PHP 5.4.
So, str_replace('\\/', '/', $pl2); would be helpful.
You'll have to decode it before usage.
json_decode()
That's what json_encode is supposed to do. Once you json_decode or JSON.parse it, it's fine.
var f = {"a":"\/users\/crazy_bash\/online\/test\/"}
console.log(f.a); // "/users/crazy_bash/online/test/"
var h = JSON.parse('{"a":"\/users\/crazy_bash\/online\/test\/"}');
console.log(h.a); // "/users/crazy_bash/online/test/"
I had the same problem, basically you need to decode your data and then do the encode, so it works correctly without bars, check the code.
$getData = json_decode($getTable);
$json = json_encode($getData);
header('Content-Type: application/json');
print $json;
I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array