Converting JSON to UTF-8 issues in PHP - php

So I have this program that allows a user to enter information into a form and upon submission turns that information into a JSON file. When a user goes to a different part of the program, the programs retrieves the JSON file and builds a questionnaire out of it.
The building of the JSON file works fine but whenever I try to retrieve the file I'm getting an error that the JSON is returning as ASCII and as NULL. I've done my homework and saw that this usually happens when their is an encoding conflict(even though ASCII is a subset of UTF-8...).
So I made sure that when creating the file I'm using using mb_convert_encoding($x, 'UTF-8', 'auto');
to ensure that the JSON is properly being encoded as UTF-8.
I was also using mb_convert_encoding when retrieving the JSON, but saw that double encoding can cause issues so when I removed that piece it no longer echoed out what the encoding was(using mb_detect_encoding) but it is still NULL.
I even went so far as to pull down the JSON file, save it as UTF-8 and re-upload it.
Any and all help on this is much appreciated it. I've banged my head for two days over this. This is built in Code Ignitor, if that makes a difference
Here is the code to create the JSON file:
$thisClient = $this->input->cookie('client');
$date = "%m-%Y";
$date = mdate($date);
$clientDir = *********PATH TO CREATE THE DIRECTORIES IN;
$dialogDir = $clientDir."/".$date;
$d_file_name = $thisClient.'-'.$date;
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($clientDir)){
mkdir($clientDir, 0755, TRUE);
echo "Client Directory Created!<br>";
} else{
echo "No Client Directory Created!<br>";
}
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($dialogDir)){
mkdir($dialogDir, 0755, TRUE);
echo "DIALOG Directory Created!<br>";
} else{
echo "No DIALOG Directory Created!<br>";
}
$custDialog = array();
if(isset($_POST['cust-dialog-title'])){
function encodeMe($x){
//this ensure proper encoding
return mb_convert_encoding($x, 'UTF-8', 'auto');
}
$customDialog = array();
for($i = 0; $i < count($_POST['cust-dialog-title']); $i++){
$customDialog[$i]["title"] = encodeMe($_POST['cust-dialog-title'][$i]);
$customDialog[$i]["intro"] = encodeMe($_POST['cust-dialog-intro'][$i]);
for($ii = 0; $ii < count($_POST['cust-dialog-quest-'.$i]); $ii++){
$customDialog[$i]["questions"]["q".$ii] = encodeMe($_POST['cust-dialog-quest-'.$i][$ii]);
if($_POST["cust-dialog-pos-".$i."-".$ii] == "TRUE"){
//if the question is a true positive
$customDialog[$i]["questions"]["agree"] = -5;
$customDialog[$i]["questions"]["disagree"] = 5;
} else{
//if the question is a false positive
$customDialog[$i]["questions"]["agree"] = 5;
$customDialog[$i]["questions"]["disagree"] = -5;
}
}
$jsonDIALOG = json_encode($customDialog);
$jsonDIALOG = str_replace("[", " ", str_replace("]", " ", $jsonDIALOG));
if ( ! write_file($dialogDir."/".$d_file_name.".json", $jsonDIALOG )) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
//save Custom DIALOG info in database
***********DATABASE INFO**************
}
}
Here is the code to retrieve the JSON object:
if($row["custom"] !== null){ //If the Dialog is a Custom Dialog
$path = str_replace(*****removes an unnecessary portion from the path string**);
$thisDialog = file_get_contents(****PATH TO JSON FILES*****);
//THE FOLLOWING helps debug issues with the JSON -- displays order number and dialog being called -- uncomment to use
//echo $i.' is '.$curDialog[$i]. '<br>';
//$thisDialog = substr($thisDialog,1);
//echo $thisDialog;
//THIS IS THE CODE FOR DEBUGGING ENCODING ISSUES
//$thisDialog = mb_convert_encoding($thisDialog, 'UTF-8', 'ASCII');
//echo mb_detect_encoding($thisDialog);
$jsonDialog = json_decode($thisDialog, true);
echo var_dump($jsonDialog);
if($jsonDialog){
$allDialogs = $jsonDialog;
} else {
echo "Error: Invalid Dialog. Call Order# 0<br>" ;
}
return $allDialogs;
}
I've included some debugging things that I've tried and commented out. Thanks!!

You should probably add JSON_UNESCAPED_UNICODE as an option to json_encode. Keep in mind that this constant is available since PHP 5.4.0

Related

How to add an error handling to read an XML file in php?

I am developing a PHP script that allows me to modify tags in an XML file and move them once done.
My script works correctly but I would like to add error handling: So that if the result of my SQL query does not return anything display an error message or better, send a mail, and not move the file with the error and move to the next.
I did some tests but the code never displays the error and it moves the file anyway.
Can someone help me to understand why? Thanks
<?php
}
}
$xml->formatOutput = true;
$xml->save($source_file);
rename($source_file,$destination_file);
}
}
closedir($dir);
?>
Give this one a try
$result = odbc_fetch_array($exec);
if ($result === false || $result['GEAN'] === null) {
echo "GEAN not found for $SKU_CODE";
// continue;
}
$barcode = (string) $result['GEAN'];
echo $barcode; echo "<br>"; //9353970875729
$node->getElementsByTagName("SKU")->item(0)->nodeValue = "";
$node->getElementsByTagName("SKU")->item(0)->appendChild($xml->createTextNode($result[GEAN]));

Modifying json with PHP not saving/updating

I am trying to modify data in a json file with php. The code I am using is below. It is able to successfully ready the file contents and in the foreach loop it will echo out in the if statement.
This is great, the if statement is hardcoded for now to test. What I want to do is modify various properties and write it back to the file. This does not seem to be working. When I load the page, then refresh to see if the new value was set it just keeps echoing the same values. I download the .json locally and nothing has changed.
Any thoughts on what I am doing wrong?
//Get file, decode
$filename = '../json/hartford.json';
$jsonString = file_get_contents($filename);
$data = json_decode($jsonString, true);
foreach ($data['features'] as $key => $segment) {
if ($segment['properties']['UID'] == '25301') {
//echo out properties for testing
echo("KEY: ".$key."<br/>");
echo("UID: ".$segment['properties']['UID']."<br/>");
echo("Full Name: ".$segment['properties']['FULLNAME']."<br/>");
echo("FCC: ".$segment['properties']['FCC']."<br/>");
echo("Render CL: ".$segment['properties']['RENDER_CL']."<br/>");
echo("<hr/>");
//set property to new value.... NOT WORKING?
$segment['properties']['RENDER_CL'] = 111;
}
}
//Test if file is writable to be sure
$writable = ( is_writable($filename) ) ? TRUE : chmod($filename, 0755);
if ( $writable ) {
$newJsonString = json_encode($data);
if (file_put_contents($filename, $newJsonString)) {
echo('Put File Content success');
} else {
echo('NOT put');
}
} else {
echo 'not writeable';
}
In the end it will echo out 'Put File Content success' which seems to indicate it was successful but it isn't... Thanks for any advice.
You need to understand how foreach cycle works. The thing is, that the value you're getting ($segment) is a copy of the real value in the source array. So when you assign to it ($segment['properties']['RENDER_CL'] = 111;), you don't really change the source array. You only change some local variable that goes out of scope when the cycel-loop ends.
There are several ways how to solve this issue. One of them is to add & before the value-variable:
foreach ($data['features'] as $key => &$segment)
This tells it to use the reference of the array-item, not to copy its value.
You should use $segment variable in foreach as a reference:
foreach ($data['features'] as $key => &$segment) {
...
$segment['properties']['RENDER_CL'] = 111;
}

PHP Not loading rest of page after exit;

I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.

Having trouble getting the right idea

well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories