php - encode json to path - php

I have a JSON file and in it consists of site data. This site data is for a homepage (I decode the JSON into variables so I can echo them out within the HTML).
Here is my code:
<?php
//start json stuff
$path = "../assets/json/home.json";
$fileexists = file_exists($path);
if ($fileexists) {
$json_d = file_get_contents($path,TRUE);
$json = json_decode($json_d,TRUE);
} else {
die("Error retrieving site data - please refresh the page. If that doesn't work, please report a problem, here and come back later.");
}
if(isset($_POST['submit'])) {
$navtitle = $_POST['navtitle'];
$title = $_POST['title'];
$json_arr = array('navtitle' => $navtitle, 'title' => $title);
$json_enc = json_encode($json_arr);
$json_result = file_put_contents($path, $json_enc);
if($json_result) {
echo "<script>alert('WORKING!');</script>";
} else {
echo "<script>alert('NO WORKING!');</script>";
}
}
?>
So, I have created the array, encoded the array and placed it in the file (I think) but I do not see any changes.
NOTE: I have added the <meta http-equiv="expires" content="0"> meta tag to force the website/browser to grab the home.json file everytime the page is loaded in.
Thank you for any help.

Related

HTML function to download JSON stored in MySQL database

I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D

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;
}

Russian Characters in URL PHP

I have scoured the internet and I'm either not finding the answer or I'm unable to implement it correctly.
Basically I am trying to implement a website in Russian on PHP. I have already got the website in English and French but bringing a whole new range of characters in has sort of broken the test site. My actual goal is to have the Cyrillic characters in the URL, similar to how Wikipedia are able to do it > https://ru.wikipedia.org/wiki/Компьютер and also still find this in the database to show the correct location information.
In my SQL database I have a range of locations, countries such as France, Germany, Australia etc. I have set it up so that the location page is generated dynamically from those entries using the $data['Name'] variable. Now... in the header.php file I use this to generate the location names from the database for the navigation:
<li class="dropdown">
Места
<ul>
<?php if (is_array($locations)) {
foreach ($locations as $key => $location) {
$name = strtolower(str_ireplace(" ","-", $location['name']));
if ($location['top_location'] == 1)
echo '<li>'.$location['name'].'</li>';
}
}
?>
</ul>
</li>
Where $name is replaced by database entries. If I change one of the database entries to Russian (Australia for example - Австралия) then the location page throws a 404 error as it's actually trying to find location/%D0%90%D0%B2%D1%81%D1%82%D1%80%D0%B0%D0%BB%D0%B8%D1%8F rather than location/Австралия.
My location page has the following code to get information from the database:
<?php
include './inc/utils.php';
if (isset($_GET['id'])) {
$name = str_ireplace("-"," ", $_GET['id']);
$result = get_data("Locations", array("name" => $name))[0];
}
else
$result = null;
if ($result != null) {
$data['Name'] = $result['name'];
$data['Url_Name'] = $_GET['id'];
$data['Image'] = $result['image'];
$data['Slider_Text'] = $result['slider_text'];
$data['Description'] = $result['description'];
$data['Country'] = $result['top_location'] != 0 ? true : false;
$data['Cars_In_Location'] = get_cars_in_location($result['id']);
$img_url = $MASTER['car_img_url'];
$link_url = $MASTER['base_url'].'car/';
$cities_id = explode(",", $result['related']);
foreach ($cities_id as $value) {
$data['Related'][] = get_data("Locations", array("id" => $value))[0];
}
}
else {
$data['Name'] = "";
$data['Url_Name'] = "";
$data['Image'] = "";
$data['Slider_Text'] = "";
$data['Description'] = "";
$data['Country'] = false;
$data['Related'] = "";
$data['Cars_In_Location'] = "";
}
if (empty($data['Name']) == true) {
header('HTTP/1.1 404 Not Found');
header('Location: '.$MASTER['base_url'].'404.php');
}
include 'header.php';
?>
I have tried using urldecode to no avail. I think I am missing something either on the SQL side or in one of the function files.
my header.php file contains both
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> and
header('Content-Type: text/html; charset=utf-8');
as well as my location page containing
header('Content-Type: text/html; charset=utf-8');
my .htaccess file has
AddDefaultCharset UTF-8
I don't know what else I'm missing.
You can see the page here:
https://redfoxluxurycarhire.com/ru/location/Австралия
I am using print_r($host_url) to correctly print the URL despite what it shows so you can see my issue. I am also able to echo Австралия onto the location pages with no problems or encoding.
Any help would be much appreciated as I'm wracking my brain as how to get this to work!
I would start checking if you have any file-systems encoding problem. Check your scripts are using UTF-8, I believe your MySQL database is OK. You should be able to decode requests with urldecode.

Converting JSON to UTF-8 issues in 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

Multiple save on upload plus save on database errors

I have set of questions have you ever encounter some issues when multiple save on database?my problem is this, i have a database called "album" where fields are 'album_id,album_title,album_user'.
The html output would be there is a login section where there is a input type file where you want to add more and once you have uploaded it. and array of set of names will be stored and that array will be our que to save the file on the multiple format the problem is that. it says and error on the database whichs is sql specified twice.Do you have an idea on how to save in multiple using php?
code will be like this.
<?php
class Album extends olib{
function __construct(){
parent::olib();
}
function upload_submit() {
$allow = array("jpg","png","gif");
$directory = "upload";
$pictures = array();
$counter = 0;
$error = '';
if($this->jpost('upload')) {
for($getupload = 0;$getupload<count($_FILES['uploadpictures']['name']);$getupload++){
$extension = end(explode(".",$_FILES['uploadpictures']['name'][$getupload]));
if(in_array(strtolower($extension),$allow)){
if(move_uploaded_file($_FILES['uploadpictures']['tmp_name'][$getupload],$directory."/".$_FILES['uploadpictures']['name'][$getupload])){
$pictures[$getupload] = $_FILES['uploadpictures']['name'][$getupload];
$counter++;
// $this->save_user_album($_FILES['uploadpictures']['name'][$getupload],$this->setSession('user_id'));
}else{
$error[$getupload] = "Sorry seems some of the data invalid";
}
}else{
$error = '1';
}
}
print_r($pictures);
print_r($error);
foreach($pictures as $urpics){
$this->save_user_album($urpics,$this->setSession('user_id'));
}
}
}
function save_user_album($albumtitle,$session){
$_firewall = ($this->setSession('user_id') !=="") ? $this->setSession('user_id') : "";
$this->jfields('album_pics_title',$albumtitle);
// $this->jfields('album_pics_user',$session);
return $this->jSave('album_pics');
}
}
any response will greatly appreciated!!
Hi I'm sorry seems i have a solution for this i have unset after it has been save..
unset($this->jfields); problem has been solved

Categories