Convert string to JSON and save as .json file in php - php

I have a JSON Object. I converted it to string to send data to another page.
I again want to convert that data to JSON and store in a JSON file.
dwv.min.js:
this.onStateSave=function(){
var e=new H.State;
var new_json = e.toJSON(o);
var myJSON = JSON.stringify(new_json);
jQuery.post("add_annotation_script.php",
{myJSON:myJSON}
);
}
add_annotation_script:
$myJSON = (String)$_POST['myJSON'];
$rad = $_SESSION['rad_id'];
$image = $_SESSION['image'];
$case_id = $_SESSION['case_id'];
$jObj = json_decode($myJSON);
$path = "C:/wamp64/www/MIC/anno/".$case_id."/".$image.$case_id.".json";
$f = (file_exists($path))? fopen($path, "a+") : fopen($path, "w+");
fwrite($f, $jObj);
fclose($f);
Is this correct or I am missing anything out?
Errors:
Undefined index: myJSON

Related

Is there a way to convert to json object in php

I have this in my text tile
[{"id":20,"tokenType":"Keyfob","tokenValue":"9037119","isLost":false}][{"id":22,"tokenType":"Keyfob","tokenValue":"47690743","isLost":false}]
But i am trying to convert it to json object like this below:
$cache_file = $_SERVER['DOCUMENT_ROOT']."/site/users/sample-keys-test.txt";
$file = fopen($cache_file, "r");
$file_content = fread($file, filesize($cache_file));
$file_content = preg_replace("/\[(.*?)\]/", "$1,", $file_content);
$file_content = rtrim($file_content, ",");
$data = json_decode("{\"items\": [".$file_content."]}", true);
var_dump($data);
foreach($data["items"] as $json_object) {
// Do something with each JSON object
echo $json_object["id"]."<br>";
echo $json_object["tokenType"]."<br>";
echo $json_object["tokenValue"]."<br>";
echo $json_object["isLost"]."<br>";
}
fclose($file);
But in the line with var_dump i get null which means there is something wrong with converting it to json object.

Flutter web file upload

void _uploadFile(Event event) async {
print("called");
final files = uploadInput.files;
final file = files![0];
_fileNameController.text = file.name;
// Get the file contents as a List<int>
final reader = new FileReader();
reader.readAsArrayBuffer(file);
await reader.onLoad.first;
final contents = reader.result as List<int>;
// Encode the file contents as a base64 string
final encodedFile = base64Encode(contents);
var response = await http.post(Uri.parse("http://url/img_test/img.php"),
body: jsonEncode(<String, String>{
'file': encodedFile,
})
);
print(response.body);
if (response.statusCode == 200) {
// Handle the success case
print("ok");
} else {
// Handle the error case
print("try");
}
}
I all ready set as file in body but till it shows
Error shows in flutter
Warning: Undefined array key "file" in M:\WEB\htdocs\img_test\img.php on line 7
PHP API:
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
?>
your request post not send file, this string value, you can try decode in your php file like this
$base64string = "data:image/jpeg;base64,".$POST['file'];
list($type, $base64string) = explode(';', $base64string);
list(,$extension) = explode('/',$type);
list(,$base64string) = explode(',', $base64string);
$fileName = uniqid()'.'.$extension;
$imageFile = base64_decode($base64string);
file_put_contents($path.$fileName, $imageFile);

Modify text file with php code

I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.

Decode Base64 string in PHP recieved from JSON post

I'm working on a project where i can select an image (simple file select) and send it via JSON to a PHP MySQL insert page.
Upload page looks like this:
if (input.files && input.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
var Naam = $('input[type=file]').val();
$('#base').text(e.target.result);
var Foto = e.target.result;
var Barcode = $('#barcode').val();
obj['Barcode'] = Barcode;
obj['Naam'] = Naam;
obj['Foto'] = Foto;
//execute ajax send
$.ajax({
url : 'insert.php',
type : 'POST',
data : obj,
dataType : 'json',
success : function(msg) {
alert("msg");
}
});
//$.post("insert.php", obj, function (data) {}, "json");
//alert("msg");
};
FR.readAsDataURL(input.files[0]);
and my PHP page:
$Barcode = $_POST["Barcode"];
$Naam = $_POST["Naam"];
$Name = preg_replace('/^.+[\\\\\\/]/', '', $Naam);
$Foto = base64_decode($_POST["Foto"]);
$query = "INSERT INTO voorraad_foto (barbody, location, foto) VALUES ('$Barcode','$Name','{$Foto}')";
$results = mysqli_query($db,$query);
And my table field is a BLOB.
But when it execute this, everything works fine except that it doesn't insert it as a blob, but pure string
I've tried with removing the
preg_replace('#data:image/[^;]+;base64,#', '', $Foto)
but doesn't make any difference, same when trying to add headers, but nothing..
What am i doing wrong, or is there something obvious that i'm not getting?
Thx.
I solved it in some kind of way:
I wrote a function that gets the Base64 string, decodes it and writes it to a Temp file.
Then i read that file again and upload that to my databse.
When success, delete the file.
It may not be the most effecient way, but it works!
function WriteToImageAndGetData($base64_string, $File) {
//Write to file
$ifp = fopen($File, "wb");
$data = explode(',', $base64_string); //Split Base64 string
fwrite($ifp, base64_decode($data[1])); //Decode Base64 string
fclose($ifp);
//Read from file
$fp = fopen($File, 'r');
$data = fread($fp, filesize($File)); //Read file contents
$data = addslashes($data);
fclose($fp);
return $data;
}

How can I get some text from data uri and assign to an array?

my data
this1
this2
this3
this4
what I want
$keepit[0]='this1';
$keepit[1]='this2';
$keepit[2]='this3';
$keepit[3]='this4';
data uri
data:text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=
Is it possible to do this?
You can do this with normal file methods using the data:// protocol:
$data = file('data://text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
Alternatively though you can pull out the base64 encoded string and decode it yourself:
$plaintext = base64_decode('dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
If the encoded string can be decoded this will work:
$file_path = ''; // change this.
$fp = fopen($file_path, 'rb');
$contents = fread($handle, filesize($file_path));
fclose($fp);
$data_uri = preg_split('/,/', $contents);
$encoded = $data_uri[1];
$decoded = base64_decode($encoded);
var_dump($decoded);

Categories