PHP & JSON : Trying to write JSON to Mysql - php

I am having an issue where my PHP script opens a file with JSON code and needs to insert it into a MySQL database.
For some reason it only displays some of the output from the JSON.
Here is my code
$json = json_decode(file_get_contents('data.json'), true);
$data = $json;
// VAR's
$system = $data['System'];
$cid_from = $data["From"];
$cid_to = $data['To'];
//DEBUG USAGES
$array = print_r($data, true);
////// THIS ONE WORKS FINE
echo $data["System"];
////// THIS ONE DOESN'T WORK
echo $data["To"];
file_put_contents('output/json-local.txt',$array . "\r\n", FILE_APPEND);
////// BUT HERE IT ACTUALLY WORKS
file_put_contents('output/cli-from.txt',$data['From']. "\r\n", FILE_APPEND);
file_put_contents('output/cli-to.txt',$data['To']. "\r\n", FILE_APPEND);
// file_put_contents('json-sysid-local.txt',$systemid . "\r\n", FILE_APPEND);
Here is the contents of data.json
{"action":"call-data-record",
"System":"48130b83e2232f0ecd366a92d4d1261d",
"PrimaryCallID":"n1bWEfCdHcf#MSS.MTN.CO.ZA-b2b_1",
"CallID":"0440b807#pbx",
"From":"<sip:+27722080036#xxx.co.za>",
"To":"<sip:27102850816#xxx.co.za>",
"Direction":"O",
"RemoteParty":"",
"LocalParty":"",
"TrunkName":"",
"TrunkID":"",
"Cost":"",
"CMC":"",
"Domain":"xxx.co.za",
"TimeStart":"2018-08-14 16:03:21",
"TimeConnected":"",
"TimeEnd":"2018-08-14 16:03:23",
"LocalTime":"2018-08-14 18:03:21",
"DurationHHMMSS":"0:00:00",
"Duration":"0",
"RecordLocation":"",
"RecordUsers":"",
"Type":"hunt",
"Extension":"100",
"ExtensionName":"100",
"IdleDuration":"",
"RingDuration":"2",
"HoldDuration":"0",
"IvrDuration":"0",
"AccountNumber":"400",
"IPAdr":"",
"Quality":"VQSessionReport: CallTerm\r\nLocalMetrics:\r\nCallID:0440b807#pbx\r\nFromID:<sip:27102850816#xxx.co.za>\r\nToID:<sip:+27722080036#xxxx.co.za>;tag=1460166964\r\nx-UserAgent:Vodia-PBX/57.0\r\nx-SIPmetrics:SVA=RG SRD=91\r\nx-SIPterm:SDC=OK SDR=OR\r\n"}

Your "To" data is encapsulated in <>. This causes your browser to interpret it as an HTML tag and not display any content.
You can (should!) escape the special HTML control characters:
echo htmlspecialchars($data["To"]);
See http://php.net/htmlspecialchars
Edit: It doesn't hurt to precautionary add this to your other outputs aswell. If the string doesn't contain such characters, it will simply be returned onchanged. You eliminate possible XSS attack vectors this way.

The browser source clearly shows "To":"" is being written by PHP to the browser output correctly but the browser is interpreting as an HTML opening tag hence ignoring the rest of the content.
Wrap your output in the PHP htmlspecialchars() function to see the output as in the file.
Add - echo "TO : ".htmlspecialchars($data["To"]);

Related

Create a PHP file using PHP?

I'm planning about creating a simple script that will allow unexperienced in PHP users create a code files for one video game. I have two files, "code.txt" and "exec.php". The first file looks like this:
getglobal_move_call("TurnTarget")
getglobal_move_loadk_call("GenerateCSM", "15")
And "exec.php" creates a "temp.php", that imports the user made file. It's filled with "str_replace" functions, and results supposed to look like this:
<?
$temp_line = "TurnTarget(param1)";
file_put_contents($generated_output, $temp_line, FILE_APPEND);
$temp_line = "GenerateCSM(param1, 15)";
file_put_contents($generated_output, $temp_line, FILE_APPEND);
?>
But, when I echo my code after these replacements, I'm getting this:
<?
= "TurnTarget(param1)";
file_put_contents(User/Apple/Sites/Generate/Generated.txt, , FILE_APPEND);
= "GenerateCSM(param1, 15)";
file_put_contents(User/Apple/Sites/Generate/Generated.txt, , FILE_APPEND);
?>
As you can see, str_replace deleted all variables. Is there a solution to this?
It's because you use "" in your code, and PHP replaces $temp_line with it's actual value (null, because there is no such var).
To echo PHP code escape your $ with \
Live demo
$code = <<< PHP
\$temp_line = "TurnTarget(param1)";
file_put_contents(\$generated_output, \$temp_line, FILE_APPEND);
\$temp_line = "GenerateCSM(param1, 15)";
file_put_contents(\$generated_output, \$temp_line, FILE_APPEND);
PHP;
echo $code;
Fixed the problem by separating "$" symbol and variable's name.
str_replace("templine", "$"."templine", $code);

newline in json_encode() output

I am building an output array like so
if (count($errors)) {
$success = 'false';
$output['json_msg'] = "Please try your submission again.";
$output['errors'] = $errors;
} else {
$success = 'true';
$output['json_msg'] = "Thanks for Becoming a NOLA Insider!";
}
$output['success'] = $success;
header('Content-type:application/json;charset=utf-8');
if (count($errors)) { http_response_code(500); }
echo json_encode($output);
exit;
But when I look at the response in Chrome's Network pane of the developer tools I see what appears to be a newline in response:
I tried wrapping json_encode() in trim() but this gave garbled output.
How do I eliminate the carriage return?
You can try to remove new line using str_replace
$output = str_replace(array("\r\n", "\n", "\r"),'',$output);
echo json_encode($output);
Do you have a ?> at the end of your PHP file and what's happening when you remove it ?
Because you may have a carriage return at the end of the script which may be sent before your response :
?>\n
// END OF FILE
This is explained by the fact that PHP is actually a templating language :
Here is a file which defines a function and which displays a text :
<?php
/**
* #File lib.php
*/
function sayHello()
{
echo "hello";
}
?>
forgotten text
And here is a file that includes this file.
<?php
/**
* #file index.php
*/
include_once('lib.php');
sayHello();
This will output :
forgotten text
hello
The "forgotten text" is output when the lib.php file is included whereas the "hello" is output after.
(But it may be even simpler and just the point that #nanocv suggested)
If you are getting the new line characters like \r\n to your json code after json_encode() you can follow up the method with the final json_value that you get. This will remove up all the new lines that has been output-ed from the code that you obtain after you perform the json_encode().
Hence you need to preg_replace() the json outputed value as follows which will remove uo the new lines from the json_code.
This will replace the new lines with no value over to the second parameter in preg_replace().
Try not to provide any white spaced between the php codes (i.e) Opening and Closing Codes that you process either at the beginning or at the end of the document. This may cause the issue sometimes.
Code:
$output_json = preg_replace("!\r?\n!","", $output_json);
I bet your php code starts this way:
1. <--- Note the blank line here
2. <?php
That's a new line character that will became part of the result.
(This way I could recreate the same behavior)
I solved by removing spaces from the php file indicated in the include .

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

remove \r\n from output

I know this question has been asked before but the answers are not the solution to my problem.
When i post a text with this code:
$info=html_entity_decode(mysql_real_escape_string($_POST['info']));
Like :
fdsa
fdsa
fasf
and when i posted this text with antered and spaces it looks like this
<?php echo $info;?>
fdsa\r\nfdsa\r\nfasf\r\n
i try this nl2br($info) but still not working.
What do I need to appear in the text in this way?
fdsa
fdsa
fasf
Replace the \r\n by <br>, the \n by <br>, then the\r by <br>:
$info = html_entity_decode($_POST['info']);
$info = str_replace('\r\n' , '<br>', $info);
$info = str_replace('\n' , '<br>', $info);
$info = str_replace('\r' , '<br>', $info);
$info = html_entities($info);
echo $info;
You have to make multiples replacements since new lines can be represented differently according to the operating system (See this page for more details)
Finally, sanitize the value with html_entities before echoing it, preventing client side attacks.
EDIT : Removed the mysql_... function, not needed (the value isn't intended to be inserted in a MySQL database, not now at least).
Also, read Lashus advice bellow and apply it ;)

I can't get asXml to return like it should

I have some straightforward code, which should return an xml string, but when i run this it returns only:'132963660013292910001330196400' which is all three of the second chile of all three concerts concatenated together. This is literally copied straight out of a textbook so i don't see how i could be doing it wrong to get this result. What am I misunderstanding here?
$simplexml = new SimpleXMLElement(
'<?xml version="1.0"?><concerts />');
$concert1 = $simplexml->addChild('concert');
$concert1->addChild("title", "The Magic Flute");
$concert1->addChild("time", 1329636600);
$concert2 = $simplexml->addChild('concert');
$concert2->addChild("title", "Vivaldi Four Seasons");
$concert2->addChild("time", 1329291000);
$concert3 = $simplexml->addChild('concert');
$concert3->addChild("title", "Mozart's Requiem");
$concert3->addChild("time", 1330196400);
echo $simplexml->asXML();
/* SHOULD output:
<concerts><concert><title>The Magic Flute</title><time>1329636600➥
</time></concert><concert><title>Vivaldi Four Seasons</title>➥
<time>1329291000</time></concert><concert><title>Mozart's Requiem➥
</title><time>1330196400</time></concert></concerts>
*/
Sounds like you're viewing the output of your script via a browser and it's attempting to interpret the document as HTML (the default content-type for PHP scripts).
Add this anywhere before your last line (the echo line)
header('Content-type: text/xml');
Alternatively, if you would like to see this as an HTML document, try this one
echo '<pre>', htmlspecialchars($simplexml->asXML()), '</pre>';
Demo here - http://codepad.viper-7.com/BJ2adH

Categories