Hiding a PHP JSON output from showing in view source - php

I would like to hide my JSON php output in view source, I am working with amCharts and have created PHP data sources that pull the data from a mySQL database and format it to JSON format so that amcharts can read it. Is it possible to hide the formatted JSON data in view source and still have amcharts read it.
My PHP code below. Your help is greatly appreciated.
<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', 'VPM2014' )
or die( 'Could not connect: ' . mysql_error() );
// Select the data base
$db = mysql_select_db( 'vpm_global', $link ) or die ( 'Error selecting database \'vpm_global\' : ' . mysql_error() );
// Fetch the data
$query = "SELECT Price_date, ZAR_Based_1000 FROM gso ORDER BY Price_date ASC";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_array( $result ) ) {
echo $prefix . " {\n";
echo ' "date": "' . $row['Price_date'] . '",' . "\n";
echo ' "value": ' . $row['ZAR_Based_1000'] . '' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
// Close the connection
mysql_close($link);
?>

There is no way to hide the source and provide your charts with JSON data. If you don't output the JSON, your charts won't have any data.

The only way to hide the JSON data and provide the chart would be to create the chart server-side as, say an image, and use HTML to display that image to the user.
Because the chart library you are using is client side javascript, the JSON must also be available to the client and thus visible to the browser using 'View Source' or other DOM debug tools.

You can't really send data to client and expect you still have a control over what he does with it. You can only make it a tiny bit harder to steal the data. Like by checking HTTP Refere header. Or by scaring the client with a warning about legal stuff and going to court etc. But still, none of these will stop more then 20% of internet population from eventual successful thief.
The only true solution would be, like others said, to not send him these data. Like, to generate the chart on the server (somehow) and send to the client only result as a picture. That way he won't get the raw data, just the graph visualization (at least until he hacks your server).

Related

PHP->JSON Encoding not working

I know this has been asked like a million times now.
I tried several solutions I found here but still it doesn't work for me.
What i want to do is SELECT Values out of a simple MySQL Table.
The Values are inserted every five minutes by a program I have written.
I catches all mp3 files in a selected folder and inserts its ID3 Tags into the Table tb_song.
These files should then be SELECTED with the PHP Script and an Android App should Play these files with their URL.
The Database and PHP Code works.
If I just echo all selected values it works fine.
But converting and printing out the encoded array just throws an blank screen.
Could it be that JSON Objects are limited to size?
I've got about 500 entries in tb_song.
Here's my code.
<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);
$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);
while($row=$result->fetch_assoc())
{
$temp=array();
$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];
array_push($songs,$temp);
}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
$connection->close();
?>
You can distil your code down to this. Plus adding some error checking!
<?php
/* add next 2 lines while testing,
especially if you are using a live hosting site
where error reportinf will be turned off
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
// Check connection is good
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();
$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);
if ( ! $result ) {
echo $connection->error;
exit;
}
while($row=$result->fetch_assoc()) {
$songs[] = $row;
}
$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;
//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>
I finally figured it out.
I guess this is not the standard which's happening to all people but anyway.
Before I'll post my code I want to say a few things for people who are running into the same problem:
Make sure you're only passing strings without 'ä','ü' or whatever letter that is not in the english alphabet.
You need to give your JSON Object a Name, otherwise it could cause problems.
<?php
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();//Create Array
$sql = 'SELECT * FROM tb_song';
$result = $connection->query($sql);
while($row=$result->fetch_assoc()){
array_push($songs,$row);//Insert $row in $songs
}
echo json_encode(array('Songs'=>$songs));//Giving JSON Object a proper Name and //encode
$connection->close();
?>

Removing unwanted codes from mysgli query result

please help.
I was trying to query a mysqli database to display part of my blog articles on my main page using php. It output a messy character as shown on the link. www.myimcm.com (unwanted commas and stuffs like that. The simple code for this was:
$q ="SELECT SUBSTRING_INDEX(post_content,' ',130) AS post,(post_title) AS title,ID AS id FROM wp_posts WHERE post_type='post' ORDER BY post_date DESC LIMIT 1";
$r = #mysqli_query ($dbc, $q); // Run the query.
if ($r) { // If it ran OK, display the records.
echo '<h2>LATEST FROM OUR GUIDES</h2>';
// Fetch and print all the records:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo"<p class='title'>". ($row['title'])."</p>";
echo nl2br($row['post']);
echo ' Continue reading';
}
mysqli_free_result ($r); // Free up the resources.
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The are no latest from our blog. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
use utf-8 encoding in your webpages.
Use this code in your head section.
header("Content-Type: text/html; charset=utf-8");
Your page claims to be encoded in UTF-8, but that is not true. It contains the following octets: 85, 91, 92, a0 which (on their own) are not valid UTF-8.
They are probably from one of the Windows-125x character encodings, such as Windows-1252.
You need to set up your database to use the correct character encoding for the Database, Table, and connection. See the MySQL manual and PHP manual for details.

I'm going to be auto aupdating info from mysql. How do i get the past info to keep displaying along with the new info submitted into the database?

I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.

Dynamically update variables in external PHP XML generation script

I have a simple php script, very similar to that demonstrated in the google developers examples, which creates XML data from the results of a MySQL query. I'm then using this XML to drive a map displaying waypoints for a given itinerary.
The problem that I have at present is that whilst the page showing the waypoints works, I don't know how to dynamically update the script below with the said itinerary ID. I would normally use $_GET to pass a variable, especially with a non-sensitive ID, but as this script is a separate file to the page displaying the mapping output, I'm not sure how to dynamically update variables within it.
If someone can explain how I can pass a value to this script so as to update the itineraryID within the query that I have marked as '!!!!' it would be much appreciated.
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",'&apos;',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a mySQL server
$connection=mysql_connect ($db_host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the locations table
$query = "SELECT itinerary_link.itineraryID, itinerary_link.coursesID, itinerary_courses.coursename, courses.lat, courses.lng FROM itinerary_link LEFT JOIN itinerary_courses ON itinerary_link.coursesID = itinerary_courses.coursesID
LEFT JOIN courses ON courses.coursename = itinerary_courses.coursename WHERE itineraryID=!!!! ORDER BY coursename";
$result = mysql_query($query);
//$ti1 = "U8abKhsdiu";
//$hashed = $row['coursename'];
//$bh= sha1($hashed);
//$tileimage = sha1("$bh$ti1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// Define variables for infoWindow images
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['coursename']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
I can't comment on posts yet, or I'd just ask for clarification. But I have to make assumptions about how you are using this script:
If you accessing this script through an include in the page that uses it then you can use $_GET and $_POST in the way that you are familiar.
But I suspect that's not the way you're doing it as you said dynamically!
Which means calling the script from the page you want to update using AJAX (asynchronous javascript and xml) or jQuery's simpler ajax functions.
The idea is you call this script with jQuery or AJAX from the page you want updated and then use the results (your XML) to update the page.
These methods allow post GET and POST information to be sent as well. The examples below show their usage, but you'll have to follow the links to see the proper, full, implementation.
Whichever method you choose, at the PHP end you use the same $_GET/$_POST with which you are familiar.
AJAX: ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
full example: http://www.tizag.com/ajaxTutorial/ajax-javascript.php
jQuery: $.get("test.php", { name:"Donald", town:"Ducktown" });
full example: http://www.w3schools.com/jquery/ajax_get.asp

How can i get data from mysql table

I have a couple of easy problems.
First I am trying to get names from database where surname='lion'. I wrote php a file but it didn't work:
$con = mysql_connect("localhost","yata_ali","password");
if (!$con){
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'");
if(mysql_query){
return "$degisken";
}
mysql_close($con);
?>
I wrote this code and tried to use $degisken in my xcode project. But it didn't work.
shortly i am trying to use the names whichs surname =lion in my ios project and i know i should use url.but i couldn find the code part that return name what shall i write at the end of php code ? return or something else to use in xcode.
how can i send response in php? i wonder that. what shall i write "return $name" or something else. i know call url. but i dont know whats the full php code that i shall use
You can't use PHP in an iOS project. You'll need to write some objective-c to call a URL on a server which returns this data in some sort of format (xml? json?) and then have the iOS app parse the response.
I don't think you understand how to use the mysql_* functions in PHP. Take a look at the examples on this page for guidance: http://www.php.net/manual/en/function.mysql-query.php
$degisken= mysql_query("select name from people where surname='lion'");
if ($degisken){
while($row = mysql_fetch_assoc($degisken))
{
echo $row["name"] . "<br/>";
}
}
There are a lot of errors, in your code, but the most serious are that
(a) you are running an invalid test:
if (mysql_query){ //YOU CANNOT DO THIS
(b) You cannot return "$degisken"; because $degisken is a MySQL
resource, not a string.
(c) You should not close your mysql
connection after returning something. You don't necessarily need to
close it at all, but if you're going to, close it after the query
because anything after the return won't be evaluated (assuming the
return is triggered).
(d) If you're looking for cases where the surname='lion' then don't use wildcards in the MySQL query. where surname LIKE '%lion%' will match 'scalion','lioness','slioner', etc.
Your code should look something like this:
$con = mysql_connect("localhost","yatanada_ali","sifre");
if (!$con) {
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'") or die('Error: '. mysql_error());
if (mysql_num_rows($degisken)){
//your query could return lots of results, so you may want to loop through results:
while($row = mysql_fetch_array($query)){
$name = $row['name'];
//do something with the name... I'm going to echo it.
echo $name . "<br />";
}
}

Categories