Hello fellow developers.
In order to create an automatic Drag n 'Drop function in PHP for uploading files, I am stuck in the data update after saving a first file. Indeed, I store in my database a JSON table which contains the name of the file, its path and also its type.
It looks something like this :
{
"1": {
"name": "1",
"path": "/files/project/customer1/pictures/",
"type": "jpeg"
}
}
However, if now I add another file, I can't find a solution to add it following my JSON structure.
I would like it to follow this logic:
{
"1": {
"name": "img1",
"path": "/files/project/customer1/pictures/",
"type": "jpeg"
},
"2": {
"name": "img2",
"path": "/files/project/customer1/pictures/",
"type": "jpeg"
}
}
Here is the condition I made.
I use the MEDOO library in PHP, hence the update function.
The before function retrieves everything after the "." so recover the file type.
<?php
if ($error == "") {
echo $_FILES["$name"]["name"] . " a bien été téléchargé";
$jsonOrig = '';
$jsonOrig = $database->get($table, 'attachment', ['id' => $table_id]);
$database->update(
$table,
['attachment' => Core::jsonify(
$jsonOrig,
['name' => $this->before('.', $_FILES["$name"]["name"]), 'path' => '/files/' . $path . '/', 'type' => $ext],
1
)],
['id' => $table_id]
);
}
The jsonify function allows you to generate JSON automatically.
<?php
public static function jsonify($jsonOrig = array(), $jsonAdd, $where = "")
{
header('Content-Type: application/json');
if (!is_array($jsonOrig)) {
$jsonOrig = json_decode($jsonOrig, true);
}
if (!is_array($jsonAdd)) {
$jsonAdd = json_decode($jsonAdd, true);
}
if (empty($where)) $jsonOrig[] = $jsonAdd;
else $jsonOrig[$where] = $jsonAdd;
return json_encode($jsonOrig, JSON_PRETTY_PRINT);
}
Here is the function once used
// parameter one = input file name
// parameter two = The path where the file will be uploaded
// parameter three = table name database
// parameter four = id where add the json file in the database
$Files->addFile('file', 'projets/client2/photos', 'articles', 54);
Thank you in advance for your help.
The third parameter to Core::jsonify is the "$where", meaning the key behind which you will store your new item in the array. If you pass 1 it will always store the value behind the same key, actually overriding your previously stored item. Remove this parameter and it will properly append to the array (what is done here $jsonOrig[] when key is missing PHP appends a new item).
<?php
if ($error == "") {
echo $_FILES["$name"]["name"] . " a bien été téléchargé";
$jsonOrig = '';
$jsonOrig = $database->get($table, 'attachment', ['id' => $table_id]);
$database->update(
$table,
['attachment' => Core::jsonify(
$jsonOrig,
['name' => $this->before('.', $_FILES["$name"]["name"]), 'path' => '/files/' . $path . '/', 'type' => $ext]
//remove the ",1"
)],
['id' => $table_id]
);
}
If this doesn't work, it means that the get doesn't retreive properly existing data
Related
For a site I'm working on, a user has the option to input exercise data and it is saved to a JSON file in an array:
{
"Email": "chandlerbing#centralperk.com",
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
But what I want it to do is to be able to save it in a multidimensional array so multiple records can be put in for one user.
Example:
{
"chandlerbing#centralperk.com"
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
}
}
That way multiple records for the user are saved under one primary object to make it easier to access later. However I've never used multi-dimensional arrays before so I can't figure out how to modify my code to get this to work.
// Save data
$file = ('data.json');
$arr = array();
$new_userstats = array (
'Email' => $email,
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
);
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $new_userstats);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file,$jsondata);
If Email is the attribute to uniquely identify a user. It would be great to keep this as key of our array to easily find
and add a new data to existing file.
Now the format we would be storing in file looks like
{
"chandlerbing#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
{
"ExerciseType": "Jogging",
"DistanceTravelled": "13",
},
],
"test#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "11",
},
]
}
Now how to add new data to this file would be in following way.
// Fetch existing data
$strFile = 'data.json';
$arrExistingData = json_decode(file_get_contents($strFile), true);
// Add new data to existing data, new data would contain and object in following way
$arrNewData = [
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
];
$arrExistingData[$email][] = $arrNewData;
// Save data back to file, avoid JSON_PRETTY_PRINT to reduce the file size.
file_put_contents($strFile, json_encode($arrExistingData));
Try:
$new_userstats = array (
$email => array (
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
)
);
I have 2 different php files that am using to fetch data from an API and one JSON file for storing the data. I want that when i run each of the PHP files on the server, my Json file would store array from both PHP files. E.g:
store.json
{
"articles": [{
"author": "Rozina Sabur",
"title": "John Cleese to return to new BBC sitcom Edith - despite saying he would never be back",
"description": "Almost 40 years on from his starring role in Fawlty Towers, John Cleese is set to return to the BBC for a new sitcom.",
"url": "http:\/\/www.telegraph.co.uk\/news\/2017\/04\/11\/john-cleese-return-new-bbc-sitcom-edith-despite-saying-would\/",
"publishedAt": "2017-04-11T22:10:11Z"
}]
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
"nationality": "Spain",
"contractUntil": "2021-06-30",
"marketValue": "9,000,000 €"
}]
}
first.php
$url = ('myAPI.com');
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$values = array();
$resp = array();
$date = date('Y-m-d H:m:s');
//get the employee details
foreach ($data['players'] as $myp) {
$name = $myp['name'];
$posi = $myp['position'];
$nation = $myp['nationality'];
$market = $myp['marketValue'];
$values[] = array('name' => $name, 'position' => $posi, 'nationality' => $nation, 'marketValue' => $market, 'created' => $date);
}
$resp['players'] = $values; //HERE IS THE PART (PLATERS)
$fp = fopen('myJson.json', 'w');
fwrite($fp, json_encode($resp));
fclose($fp);
second.php The code is pretty much like that of first.php just API diff.
.......
........
$values[] = array('author' => $author, 'title' => $title, 'description' => $descrip, 'url' => $ur, 'publishedAt' => $publish);
}
$resp['articles'] = $values; //HERE IS THE MAIN POINT (ARTICLES)
$fp = fopen('myJson.json', 'w');
fwrite($fp, json_encode($resp));
fclose($fp);
My problem is, when I run first.php the array replaces that of second.php and vise versa. How to I fix it so that array from both PHP file store in the JSON file like in the store.php file above.
Other ideas on best practices other than 2 diff php files are welcome.
Thanks
Because both programs are opening the file as 'w'
Change it to this
$fp = fopen('myJson.json','a');
just as a note, this will not be a valid 'single json file', but a file of valid json lines.
$fp = fopen('myJson.json', 'a');
fwrite($fp, json_encode($resp));
fclose($fp);
use a flag to keep last data
Add this method to a PHP file and require this file in your two PHP files.
function storeJson($data, $type)
{
$prevData = file_get_contents('store.json');
$arrayData = json_decode($prevData, true);
if(in_array($type, array_keys($arrayData))) {
$arrayData[$type] = $data;
$fp = fopen('store.json', 'w');
fwrite($fp, json_encode($arrayData));
fclose($fp);
}
}
In first.php file at the end call the method
storeJson($resp, 'players');
In the second.php file
storeJson($resp, 'articles');
I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);
currently I use three separate php functions to array:
folder names
a thumbnail under the folder
a text file under the folder
into three separated json files, so they now are:
["folder1","folder2","folder3"]
["folder1/thumb.svg","folder2/thumb.svg","folder3/thumb.svg"]
["blah blah blah","blah blah blah","blah blah blah"]
This works fine for me but it would be so much easier if I can make them into one json file looks like this:
[
{
"name" : "folder1",
"thumbnail" : "folder1/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder2",
"thumbnail" : "folder2/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder3",
"thumbnail" : "folder3/thumb.svg",
"text": "blah blah blah"
},
]
Is there a way to do it? Thanks.
Explain more:
For example I tried array("name" => array_map("basename", glob('./folders/*', GLOB_ONLYDIR)),) and it just put all my folders as a giant array under one single entry of "name," like this {"name":["folder1","folder2","folder3"]}.
A pseudo solution:
IkoTikashi provided a solution, while not necessary answering the question, but could be useful to some people. I use his idea to establish some example codes below:
<?php
$checkfolder = './path/examples/folders';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$filename = $folder . "/description.txt";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
} else {
$contents = '';
}
$json[] = [
'name' => str_replace($checkfolder, '', $folder),
'thumb' => $folder . '/thumb.svg',
'text' => $contents
];
}
json_encode($json);
?>
Of course this solution isn't perfect. For one it doesn't provide usable url for thumbnails. And more importantly it erased the modularity of the original codes - that users can use three separated api to generate specific json to their need. The reason to reorganize the existing json files is that they can have an additional option to generate combined arrays. This solution, rather, created a whole new function to accomplish such goal - so while it is a temporary solution, it lacks of upgradability.
Read in all directories under folders/ and use them to set a new array:
<?php
$checkfolder = 'img/';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$folderName = str_replace($checkfolder, '', $folder);
$json[] = [
'name' => $folderName,
'thumbnail' => $folderName . '/thumb.svg',
'text' => 'blah blah blah'
];
}
print_r(json_encode($json));
Inside of that loop you would do file existance checks, reading the text etc.
json in general is a text, so, if you want to make your script a JSON data source, you are able to print it out in that format.
For example:
echo "{\n";
echo "{\n";
echo "'name':'$folderArr[0]'\n";
echo "}\n";
echo "}\n";
However, you must get sure that there's no any other text printout will be occurred on the script to avoid corruption of JSON format.
I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.