Reputation: 11
A user inputs values into a form on a Raspberry Pi and this should, in theory, convert the values to json format, write it to file, kill all of my bp sessions and start again (with a redirect to BBC as confirmation for now).
The parameters tail
, growthrate
, and fps
are being encoded as strings, not integers. The result in the final file (webtest1.json
) is that they appear as "tail": "1"
and I need "tail": 1
.
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$postArray = array(
"driver" => $_POST['driver'],
"animation" => array(
"typename" => $_POST["typename"],
"tail" => $_POST["tail"],
"growthRate" => $_POST["growthRate"]
),
"run" => array(
"fps" => $_POST["fps"]
),
"layout" => $_POST['layout']
);
//you might need to process any other post fields you have..
$json = json_encode( $postArray );
// make sure there were no problems
//if( json_last_error() != JSON_ERROR_NONE ){
//exit; // do your error handling here instead of exiting
// }
$file = '/home/pi/Documents/webtest1.json';
// write to file
// note: _server_ path, NOT "web address (url)"!
file_put_contents( $file, $json);
}
shell_exec("sudo killall bp");
shell_exec("sudo bp /home/pi/Documents/webtest1.json > /dev/null 2>/dev/null &");
header("Location: http://www.bbc.co.uk");
die();
Upvotes: 1
Views: 1461
Reputation: 38502
Way 1: If you have PHP version 5.3.3 or greater you can try like this with 2nd argument JSON_NUMERIC_CHECK
to json_encode() function without casting each and every numeric values. Need less change if you've newest php version.
Say your array is like this,
$arr = array(
"driver" => 'driver',
"animation" => array(
"typename" => 'typename',
"tail" => '1',
"growthRate" => 10
),
"run" => array(
"fps" => '23'
),
"layout" => 'layout'
);
echo json_encode( $arr, JSON_NUMERIC_CHECK );
Output:
{
"driver":"driver",
"animation":{
"typename":"typename",
"tail":1,
"growthRate":10
},
"run":{
"fps":23
},
"layout":"layout"
}
Way 2: Cast your each and every $_POST
variable values to integer type like (int)$_POST['fps']
. Also do it where you needed like for fps
, tail
or growthRate
values. This is good one but it may need to change many places on your code.
Upvotes: 4
Reputation: 21661
What @Ian Middelkamp said.
But I would add you can use (int)
casting too So stealing that example
"tail" => (int)$_POST["tail"],
Upvotes: 1
Reputation: 140
Not sure how to stop it because I can't see your web form. But, you can use intVal to convert to integer any string. as in
"tail" => intVal($_POST["tail"]),
I think that specifying type='number' on the input field might help with submitted values. worth a try
Upvotes: 2