Can't json_decode() from file - Syntax error - javascript

I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).

According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);

You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);

Related

Iterate through JSON String in PHP?

it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}
How can I iterate through this JSON string without knowing the key and value? I would like to get this output:
title -> value
title2 -> value2
I tried it this way:
$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
$response = $response. "$key : $val";
}
echo json_encode($response);
It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.
You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:
var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
console.log(key + ' -> ' + data[key]);
}
And for PHP:
You can parse the json string into an array using json_decode:
$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
echo "$key : $val";
}
true parses it into an array instead of a std object.
https://www.php.net/manual/en/function.json-decode.php
Because of response's format you must decode the decoded format in order to take the object as you want
$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
echo "$key -> $val";
}
Output :
title -> 12 title2 -> text

Receive post with description containing '%' and two letter together

I have problems with treatment of Post. I received a string with the symbol '%' and two letters together, like 'Geci%de', but on PHP the var_dump I receive a different string, like 'Geci�', if try to use utf8_encode and utf8_decode, however the error continued, the strings resulted were 'GeciÞ' and'Geci?'. How is the better way to convert in the orignal string? I need to use in postgreSQL, it will be in select.
It is uses to treatment:
$data = strip_tags($data);
$data = trim($data);
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data;
$data = preg_replace("#(--|\|)#s", "", $data);
$data = urldecode($data); // especific to Ajax
return utf8_decode($data);

Getting null in json_decode

I have a text file that has json on it. example below:
{'something' : 'ss'}
I am trying to read it on php and convert it to an array using json_decode.
$temp = '';
$fh = fopen( '/quiz' . $testid . '.txt' ,'r');
while ($line = fgets($fh)) {
$temp .= $line;
}
fclose($fh);
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
But im getting null
If I don't json_decode it.. I can get the string.
I hope anyone can help me with this.
Thanks,
E
You don't need to do any parsing prior to calling json_decode
$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);
If you're still getting null, your JSON is likely invalid, you can use json_last_error to diagnose it.
This snippet works so i think that's a problem with your file parsing algorithm
<?php
$temp = '';
$temp='{
"a":1,
"b":[1,2,3]
}';
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
var_dump($temp);
?>
As documented:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
The reason is that you don't have valid JSON.
Parse error on line 1:
{ 'something': 'ss'}
-----^
Expecting 'STRING', '}'
You probably mean:
{
"something": "ss"
}

Invalid JSON format from PHP json encode

I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}

Save javascript value as plaintext in DB

This is the problem I get, for example, when an user inputs <script>top.location.href=’http://www.google.nl’;</script>
I want my application to echo it as plain text. Now, this actually works with
htmlspecialchars()
This example works for me:
$test = "<script>top.location.href=’http://www.google.nl’;</script>";
echo htmlspecialchars($test);
But, when the user submits the form, the data goes to my DB and then returns to a 'dashboard'.
The value is now ''.
Is there a way how I can save the data safe into my DB?
I add the values into the DB for my C# application in this way via SDK:
$onderwerp = htmlspecialchars(stripslashes(trim($_POST['onderwerp'])), ENT_QUOTES,'UTF-8',true);
$omschrijving = htmlspecialchars(stripslashes(trim($_POST['omschrijving'])), ENT_QUOTES,'UTF-8',true);
$im = array('description' => mysql_real_escape_string($onderwerp),
'message' => mysql_real_escape_string($omschrijving) ,
'relation' => $_SESSION['username'],
'messageType' => 70,
'documentName' => $_FILES["file"]["name"],
'documentData' => base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$imresponse = $wcfclient->CreateInboundMessage($im);
echo $imresponse->CreateInboundMessageResult;
And then call them at my dashboard in this way:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $calls){
echo $calls->Description;
}
can you please check mysql-real-escape-string
mysql_real_escape_string() :
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
Also CHeck SQL Inject :SQL Injection
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Ouput :
Escaped string: Zak\'s and Derick\'s Laptop
Yes, read about mysqli_real_escape_string.

Categories

Resources