-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparamsToJsonFile.php
More file actions
208 lines (168 loc) · 5.78 KB
/
paramsToJsonFile.php
File metadata and controls
208 lines (168 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php
//script that will convert all POST and GET params to json format and write to a file.
//for example: use with IFTTT
//Note: POST params take priority over GET params!
//Note: a timestamp is manually added
////////// SETUP
$filename="foo.txt";
$subDirectory="./dataOut/";
$maxDataItems=50;
////////// END SETUP
$debug=false;
$showOutput=true; //set to show the output (show updates)
$addFakeData=false;
$allParams=createArrayFromParams();
/////////////// SETUP:
$ignoreParams=array(); //define the items we DO NOT want (they will be filtered)
$requiredItems=array("symbol", "start", "end", "data"); //define the items that we MUST have. data will not be added if any of these are missing e.g. array("d", "x") requires data elements: 'd' and 'x'
///////////////
if ($allParams===NULL) {
echo("No params! - Exiting.");
exit;
}
//create array with only the items that we want
$toAdd=array();
foreach ($allParams as $param_name => $param_val) {
if (!isItemInArray($param_name, $ignoreParams, $debug)) {
$toAdd[$param_name] = $param_val;
}
}
//has there been an update attempt
if (count($toAdd)>0) {
//check all is well
$approved=true;
$err="";
foreach ($requiredItems as $param_name) {
if (!isItemInArray($param_name, array_keys($toAdd), $debug)) {
$approved=false;
$err .= "missing:" . $param_name . "\n";
}
}
//debug & failed?
if ($err!="") {echo("<pre>\n" . $err . "</pre>");}
}
if ($approved) {
//manually add a timestamp
$toAdd["t"] = date("Y-m-d H:i:s");
//addJsonToFile($json);
if ($debug) {echo("Adding: <pre>" . prettyPrint(json_encode($toAdd)). "</pre>");}
addJsonToFile($toAdd);
echo("ok");
}
//var_dump($allParams);
function addJsonToFile($jsonToAdd) {
global $debug, $filename, $maxDataItems, $showOutput, $addFakeData;
$defaultFileOuter='{
"v": "1",
"d": [
]
}';
$fp = fopen($filename, "a+");
if (flock($fp, LOCK_EX)) {
$filesize=filesize($filename);
if (!$filesize || $filesize<1) {
$contents=$defaultFileOuter;
} else {
$contents=fread($fp, $filesize);
}
$json=json_decode($contents, true);
if ($addFakeData) {
$json["d"][]=json_decode('{"t": "1970-01-01 11:22:33", "d":"It\'s early days!"}');
$json["d"][]=json_decode('{"t": "1970-01-01 11:22:33", "d":"Nothing is here yet :("}');
}
$dataLength=count($json["d"]);
while ($dataLength>$maxDataItems) {
array_shift($json["d"]);
$dataLength=count($json["d"]);
}
$json["d"][]=$jsonToAdd; //add the new data
if ($debug || $showOutput) {echo("Updated:<br><pre>" . prettyPrint(json_encode($json)) . "</pre>");}
ftruncate($fp, 0); //we want to remove everything in the current file.
$contents=json_encode($json);
fwrite($fp, $contents);
//sleep(5); //can use to check that PHP works well with multiple attempts to write (PHP automatically queue's write attempts)
flock($fp, LOCK_UN);
}
}
//make sure $array is NOT an associative array - use array_keys(arrayObj) to get an array with just the keys when calling if required!
function isItemInArray($item, $array, $debug) {
$return=false;
foreach ($array as $i) {
if ($debug) {echo("testing: " . $item . "==" . $i . "<br>");}
if ($i==$item) {
$return=true;
break;
}
//var_dump($i);echo("<br>");
}
return $return;
}
function createArrayFromParams(){
//array_merge fails if 1 is empty so we need a couple of tests
if ($_POST && $_GET) {
return array_merge (
// note the sequence : POST vars overwrite any GET vars
filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS),
filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS)
);
}
if ($_GET) {
return filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);
}
if ($_POST) {
return filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
}
}
//from: https://stackoverflow.com/questions/6054033/pretty-printing-json-with-php
function prettyPrint( $json )
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}
?>