PHP - Json_encode Returning Null
Hello
I am having an issue with encoding an array to JSON, my array seems to be formed correctly but when I try and echo the json_encode version I get "null". I echo the JSON error code and it is "0" indicating no issue..
I have read that non UTF-8 characters can be an issue, but this is simple data, no strange characters... but I added the utf8_encode anyway....
Here is my code:
$dataArray = array( 'title' => 'Test Item', 'icon_url' => 'http://url/api/testimage.jpg', 'item_id' => '12345', 'expiration' => 600 ); utf8_encode($dataArray); $responsArray = array( 'success' => '1', 'data' => $dataArray ); utf8_encode($responsArray); header('Content-type: application/json'); echo print_r($responsArray); echo json_encode ($responseArray); echo json_last_error(); Similar TutorialsGood morning,
I am trying to convert a mssql query into json format so that I can then later pass this through google's visualisation api. The query and encoding seems to be working but the encode returns NULL.
I have checked the normal gotcha's of making sure its utf8 encoded and that I have used a version of PHP that has the encode (using php 5.3.19).
Can any one help me with getting the encode to work.
PHP CODE:
<?php Okay so I created a theme for my website that will also utilize a custom CMS script I developed and its not cooperating with me nicely. Here's my head of my header file for my template: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>> <head> <title><?php bloginfo('name') ?>: <?php bloginfo('description') ?></title> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> <meta http-equiv="content-type" content='<?php bloginfo("html_type"); ?> charset=<?php bloginfo('charset'); ?>' /> <?php if(is_singular()){ wp_enqueue_script('comment-reply');} ?> <?php wp_head(); ?> <?php require ('efedmanager/inc/dbconfig.php'); ?> </head> Now on my index page that calls the header file I DO NOT get a error saying that the file could not be located. So that's good news. Here's my dbconfig.php file. Code: [Select] <?php /** * @author Jeff Davidson * @copyright 2010 */ // This file contains the database access information and establishes a connection to MySQL and selects the database // Set the database access information as contstants DEFINE ('DB_USER', '?'); DEFINE ('DB_PASSWORD', '?'); DEFINE ('DB_HOST', '?'); DEFINE ('DB_NAME', '?'); // Make the database connection $dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (!$dbc) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } ?> Now when I go to one of my custom pages like this one it brings up the message: Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/xtremer/public_html/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 38 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/xtremer/public_html/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 39 Code: [Select] <div id="champions" class="content"> <h1 class="pageheading">KOW Champions and Contenders</h1> <?php $championsQuery = " SELECT titles.titleName, titles.shortName, champions.champID, champions.con1ID, champions.con2ID, champions.con3ID, biochamp.shortName AS championshortName, biochamp.characterName AS champion, biocon1.shortName AS con1shortName, biocon1.characterName AS con1, biocon2.shortName AS con2shortName, biocon2.characterName AS con2, biocon3.shortName AS con3shortName, biocon3.characterName AS con3 FROM champions LEFT JOIN titles AS titles ON titles.ID = champions.titleID LEFT JOIN characters AS biochamp ON champions.champID = biochamp.ID LEFT JOIN characters AS biocon1 ON champions.con1ID = biocon1.ID LEFT JOIN characters AS biocon2 ON champions.con2ID = biocon2.ID LEFT JOIN characters AS biocon3 ON champions.con3ID = biocon3.ID WHERE titles.statusID = '1' ORDER BY titles.ID"; $championsResult = mysqli_query($dbc, $championsQuery); while ( $row = mysqli_fetch_array ( $championsResult, MYSQLI_ASSOC ) ) { $fieldarray=array('titleName','shortName','championID','championshortName','champion','con1ID','con1','con1shortName','con2ID','con2','con2shortName','con3ID','con3','con3shortName'); foreach ($fieldarray as $fieldlabel) { ${$fieldlabel} = $row[$fieldlabel]; } ?> <div id="title"><span class="large">< ?php echo $titleName ?></span> < ?php if (file_exists('images/championshots/'.$titleshortName.'/'.$championshortame.'.png')) { echo "<img class=champion src=images/championshots/".$shortName."/".$champion.".png alt= />\n"; } else { echo "<img class=champion src=images/championshots/".$shortName."/".$shortName.".png alt= />\n"; } if (strlen ($champion) < 1) { echo "<span class=medium>Vacant"; } else { echo "<span class=medium><a href=/bio?shortName=".$championshortName.">".$champion."</a></span>\n"; echo "<span class=medium>(Since TBD)</span>"; } ?> <span class="contender">Contenders</span> <ul> < ?php if ( strlen ($con1) < 1) { echo "<li><span class=medium>TBD</span>"; } else { echo "<li><a href=/bio?shortName=".$con1shortName.">".$con1."</a></li>\n"; } if (strlen ($con2) < 1) { echo "<li><span class=medium>TBD</span>"; } else { echo "<li><a href=/bio?shortName=".$con2shortName.">".$con2."</a></li>\n"; } if (strlen ($con3) < 1) { echo "<li><span class=medium>TBD</span>"; } else { echo "<li><a href=/bio?shortName=".$con3shortName.">".$con3."</a></li>\n"; } ?> </ul> </div> < ?php } ?> </div> Hi all,
I'm posting JSON to an API call. If I use a var_dump within the API it will return correctly, although if I try to var_dump within the function it will return NULL.
API:
$json = file_get_contents('php://input'); if(isset($_GET['form_id']) && intval($_GET['form_id'])>0) { if(isset($json)) { $records = $questionnaire->logFormAnswers($_POST['answers'],$_GET['form_id']);Then using the logFormAnswers function... Function: public function logFormAnswers($answers = "", $form_id = 0) { $answers = json_decode($json,true); var_dump($answers);The JSON: [{"question_id":"3","answer":"dsf"},{"question_id":"3","answer":"sdfsdfdsfsd"}]Eventually, once the JSON has been decoded, it will be inserted into a database within the function. Trying to figure out how to better write this chunk of code. I'm wanting to get the list of the roster members and then create an array of options for the view dropdown to display inside the select dropdown and also have it have an option to display "Please Select An Option". However what if what is returned from the getAllRoster function is NULL which is what I have returned if no results are returned from a query. How should I handle that which I just want the empty option displayed. Also I need to think about is do a function to retrieve all the allies for that specific matter and then display that ally as the default ally in the dropdown for each dropdown. Controller: Code: [Select] $rosterList = $this->bios->getAllRoster(); $allies = array(); $allies[''] = 'Please Select An Opion'; foreach ($rosterList AS $ally) { $allies[$ally->id] = $ally->rosterName; } View: Code: [Select] <?php echo form_label( 'Ally 1', 'ally1'); ?> <div> <?php echo form_dropdown( 'ally1', $allies, ''); ?> </div> <?php echo form_label( 'Ally 2', 'ally2'); ?> <div> <?php echo form_dropdown( 'ally2', $allies, ''); ?> </div> <?php echo form_label( 'Ally 3', 'ally3'); ?> <div> <?php echo form_dropdown( 'ally3', $allies, ''); ?> </div> Ok, this may be just because I have been programming all day and my mind has gone blank (happens alot), but this is my PHP script: Code: [Select] <?php $query_distinct_item_types = mysql_query("SELECT DISTINCT name FROM item_types"); while($item_types = mysql_fetch_array($query_distinct_item_types)){ $distinct_item_types[] = $item_types['name']; } foreach($distinct_item_types as $item){ $query_item_total = mysql_query("SELECT item_type, SUM(price) WHERE item_type='$item' FROM costs GROUP BY item_type"); while($item_total = mysql_fetch_array($query_total_price)){ $item_totals[] = $item_total['SUM(price)']; } } $item_summery = $item_totals; ?> $item_summery which is = to $item_totals is returning null, any idea's? Hello, I'm trying to take the value from an HTML form and insert it into a database on a button click. It inserts a null value into the database. The script is called submitColumnDetails.php. This is where I create the text field that I want to take the information from. This is in a separate file. Code: [Select] echo <<<END <form action = "submitColumnDetails.php" method = "POST"> <input type = "text" name = "columnField"/> </form> END; This is the submitColumnDetails.php file Code: [Select] <?php //Submit Column Data //-----------------------------------------------------// //Connect to localhost server $connector = mysql_connect("localhost", "root", "root"); if(!$connector){ //If user can't connect to database die('Could not connect: ' . mysql_error()); //Throw an error } //-----------------------------------------------------// mysql_select_db("colin_db", $connector); $newValue = $_POST["columnField"]; //Data from column field. THIS IS WHAT RETURNS NULL $newColumnQuery = "INSERT INTO `colin_db`.`allColumnFields` (`DATA`) VALUES ('$newValue')"; mysql_query($newColumnQuery); //Query to add form to main table $newColumnIntoMainTableQuery = "ALTER TABLE colin_table ADD ('$newValue' varchar(50))"; mysql_query($newColumnIntoMainTableQuery); //Query to add column to main table mysql_close($connector); //Close database connection echo "<script type = 'text/javascript'> window.location = 'index.php'</script>"; //Go back to original page ?> Even when I print out the $newValue, it does not print anything. What am I doing incorrectly? Hi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. I am trying to update the database with isset to set the value of the variable to either null or the value entered by the user. Currently, if no value has been entered null is being set as a string causing the date field to populate with zeros. How do I code it so that it populates or sets the value as null and not as string null?
Here's my code: (yes I know sql injections it's still in development )
<?php Hey everyone. So i'm trying to json_encode one of my arrays like such:
heres an example of how the array is being created (From the array results, everything seems to be fitting OK into the actual array creation) but it's just the actual array creating a multi demension after each result.
$num = 1; $num2 = 1; $i = 0; if ($num > 0) { $array[$i][1] = 40; } if ($num2 > 0) { $array[$i][2] = 50; } ++$i;I'm trying to achive this: var array_one_results = new Array(); array_one[1][0] = 40; array_one[1][0] = 50; array_one[2][1] = 40; array_one[2][1] = 50;right now, this is my results: var array_name = new Array(); array_name["0"] = new Array();array_taken["0"]["0"] = "10"; array_taken["0"]["1"] = "20"; array_name["1"] = new Array();array_taken["1"]["0"] = "10"; array_taken["1"]["1"] = "20"; array_name["2"] = new Array();array_taken["2"]["0"] = "10"; array_taken["2"]["1"] = "20"; array_name["3"] = new Array();array_taken["3"]["0"] = "10"; array_taken["3"]["1"] = "20"; array_name["4"] = new Array();array_taken["4"]["0"] = "10"; array_taken["4"]["1"] = "20";It's creating a new array for each. If anyone could help me through this, i'd really appreciate it. I'm encoding it with this: function js_str($s) { return '"'.addcslashes($s, "\0..\37\"\\").'"'; } function js_array($array, $keys_array) { foreach ($array as $key => $value) { $new_keys_array = $keys_array; $new_keys_array[] = $key; if(is_array($value)) { echo 'array_name'; foreach($new_keys_array as $key) { echo '["'.$key.'"]'; } echo ' = new Array();'; js_array($value, $new_keys_array); } else { echo 'array_taken'; foreach($new_keys_array as $key) { echo '["'.$key.'"]'; } echo ' = '.js_str3($value).";\n"; } } } Reasons to use json_last_error() is obvious when decoding, but was not so to me when encoding. Looking at the documents, malformed UTF-8 characters will result in an error. The examples given show encoding a string, however, an array with an index value which is malformed UTF-8 characters will result in the same error. Are there other cases which json_encode() will result in error? Why would one actually want to use json_encode() on a string? Hello, I am new to pHp and javascript languages and I am trying to do some math calculations in pHp, then display the results with google charts. However, I got stuck with inserting data from pHp using json_encode. It works for the most simple array, with using 2 values. When using array of arrays, it does not work. I believe it could be a syntax errors with all those brackets but I could not figure it out. Thanks for any ideas! <?php // some arrays with dim 2x2 $testarr0 = array( 0.1, 2.5); $testarr = array( 1.0, 3.5); $testarr = array( $testarr0, $testarr ) ; // this is how it looks in pHp $json = json_encode($testarr); echo($json); echo '<br/>'; echo json_encode($json); ?> <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"> </script> <script type="text/javascript"> google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'x values'); data.addColumn('number', 'y1 '); //var dataArray = <?php echo json_encode($testarr);?>; //document.body.innerHTML = " Data Array with json: " + dataArray ; // defining array here works well /* data.addRows( [ [0.1 ,2.5], [1.0 ,3.5] ] ); */ // this here does not work: data.addRow( <?php echo json_encode($testarr);?> ); // some options for the chart var options = { chart: { title: 'Points over time', }, width: 600, height: 400, axes: { x: { 0: {side: 'top'} } } }; var chart = new google.charts.Line(document.getElementById('line_top_x')); chart.draw(data, google.charts.Line.convertOptions(options)); } </script> </head> <body> <div id="line_top_x" style="width: 900px; height: 500px"></div> </body> </html>
I have a function where I am returning a few different arrays into one return json_encode(); but how would I do this? I'm bulling an array from 2 different database tables, and I can't join or union these, because I am actually going to have quite a few different calls that needs to call into other areas. Anyway, My 2 variables are,' $names and $posts If I put one of these in the return json_encode($posts); like that, then the $posts show up fine while the names of course display Undefined, and if I put in return json_encode($names); then my code works for the names to be displayed but anything in the posts of course is undefined, how do I put these two together? Thanks Hi All I got some help to write this code and it is not working because i get the error ( ! ) Parse error: syntax error, unexpected '{' in C:\wamp\www\blackrain\Resources\json-gen.php on line 14 Here is the php code Code: [Select] <?php error_reporting(-1); ini_set('display_errors',1); $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully<br />'; mysql_select_db("php"); $arr = array(); $rs =mysql_query("SELECT `id`, `title`, `author`, `date`, `imageUrl`, `text` FROM `items`"); while($obj = mysql_fetch_array($rs,MYSQL_ASSOC) { $arr[0] = $obj['id']; $arr[1] = $obj['title']; $arr[2] = $obj['author']; $arr[3] = $obj['date']; $arr[4] = $obj['imageUrl']; $arr[5] = $obj['text']; } //numbering the array indexes, will only return 5 array indexes EVER. All indexes will be over written on each loop. echo json_encode($arr); ?> the sql data is below please put in a db named php and a table named items -- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Sep 10, 2011 at 11:49 AM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `php` -- -- -------------------------------------------------------- -- -- Table structure for table `items` -- CREATE TABLE IF NOT EXISTS `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` text NOT NULL, `author` text NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `imageUrl` text NOT NULL, `text` text NOT NULL, `catagory` text NOT NULL, KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ; -- -- Dumping data for table `items` -- INSERT INTO `items` (`id`, `title`, `author`, `date`, `imageUrl`, `text`, `catagory`) VALUES (2, 'some random title', 'me', '0000-00-00 00:00:00', 'http://forums.mysql.com/read.php?45,55300,56787#msg-56787', 'fvsdhlihldj sdfjvhduolh dvjichis', '0'), (4, '', '', '0000-00-00 00:00:00', '', '', '0'), (5, 'yet another trial', 'me', '0000-00-00 00:00:00', 'http://www.gaj-it.com/wp-content/uploads/apple5.jpg', ' nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnn', '0'), (6, 'yet another trial', 'me', '0000-00-00 00:00:00', 'http://www.gaj-it.com/wp-content/uploads/apple5.jpg', ' nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnf nnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnn', '0'), (7, '', '', '0000-00-00 00:00:00', '', ' ', '0'), (8, '', '', '0000-00-00 00:00:00', '', '', '0'), (9, 'n', '', '0000-00-00 00:00:00', '', '', '0'), (10, 'n', 'me', '0000-00-00 00:00:00', '0000', 'me', '0'), (11, 'n', 'me', '0000-00-00 00:00:00', '0000', 'me1', '0'), (12, 'M', 'Me', '0000-00-00 00:00:00', 'url', 'jdoiheouhfviuehvuiohbeuiofhvuiheiufhvuiehuifvheio uhfvoiuhrovheovhuhfvbuohouifhbouehouhbveiouhfbveb hsousuobv ousiuodfbvibfuibvousdubfdfbfbuvbbfdbufvbjjbfvdjfj fvdjfbfbfdfbbfbbfkbjkbjbfdjbjfkbjkbjbjnbjnnbdnbnj jnbdnjkbfdjknbdnjkbdnjkbdnjkbfdnjkbdnjkbfdnjkbnjk bfdnjkgbnjkgbnjknknknbngbbbd', '0'), (13, 'M', 'Me', '0000-00-00 00:00:00', 'url', 'jdoiheouhfviuehvuiohbeuiofhvuiheiufhvuiehuifvheio uhfvoiuhrovheovhuhfvbuohouifhbouehouhbveiouhfbveb h0pvipjfvoejnv oaiehnfvolijeaofvihn olan', '0'), (14, 'M', 'Me', '0000-00-00 00:00:00', 'url', 'jdoiheouhfviuejnjfnfviejnfvienfivnloidfhnvvihn olan', '0'), (15, 'hhikuh', 'h', '0000-00-00 00:00:00', 'j', ' uhuhiuhuhuiohuoiho', '0'), (16, '', '', '0000-00-00 00:00:00', '', '', '0'), (17, 'brenton', 'me', '0000-00-00 00:00:00', 'http://www.gaj-it.com/wp-content/uploads/apple5.jpg', 'hi all ', '0'), (18, '', '', '0000-00-00 00:00:00', '', '', '0'), (19, 'something', 'me', '0000-00-00 00:00:00', 'http://www.gaj-it.com/wp-content/uploads/apple5.jpg', 'ihfdvuikhavh\r\n ', '0'), (20, '', '', '0000-00-00 00:00:00', '', '', '0'), (21, '', '', '0000-00-00 00:00:00', '', '', '0'), (22, '', '', '0000-00-00 00:00:00', '', '', '0'), (23, 'cd', 'fg', '0000-00-00 00:00:00', 'srf', 'dfsf ', '0'), (24, 'cd', 'fg', '0000-00-00 00:00:00', 'srf', 'dfsf ', 'audi'); thanks matt Dear all hello. I am facing a major issue with greek characters. Here is the php script: Code: [Select] <?php $connect = mssql_connect($db_server,$db_username,$db_password) or die("0001"); mssql_select_db($wf_db) or die("0002"); $sql_a = "SELECT [ID],[WASTE_SN] FROM [Webforms].[dbo].[Waste_Types] ORDER BY [WASTE_SN] ASC"; $waste_name = array(); $waste_id = array(); $query_a = mssql_query($sql_a) or die("0003"); while ($row = mssql_fetch_assoc($query_a)){ $waste_name[] = $row['WASTE_SN']; $waste_id[] = $row['ID']; } mssql_close($connect); $final_array = array( "waste_name" => $waste_name, "waste_id" => $waste_id ); $json = json_encode($final_array); echo $json; ?> Json_encode returns null for all values of array $waste_name when greek words are found. When I use print_r($waste_name), i can see all words fine. I've tried almost everything, including utf8_encode without results. Any help will be really appreciated! when trying to decode a array of rows taken from my database I found that the json_encode function doesn't allow you to present you array as (with brackets [ ])
[{"name":"Destramic"}]but returns the array as (without brackets [ ]) {"name":"Destramic"}I looked into the documentation and it doesn't seem as if php offer such a way of having bracket which Is a bit of a problem with passing to jquery (which I've found using their autocomplete plugin) this has resulted in me having to add brackets myself $data = "[" . json_encode($rows2) . "]";does anyone know if you can encode it with the brackets or readable for jquery...thank you Hi guys, I need to know how to json_encode a mysql output, so far the PHP ref manual for json_encode is not proving very helpful. Any help is much appreciated. hi i have this code: Code: [Select] //sql $sql -> bind_param('s',$offer); $sql -> execute(); $sql -> bind_result($oferta, $cargo, $conteudo, $tipo_oferta, $local); $arr = array(); while ($sql -> fetch()) { $arr[] = array($oferta, $cargo, $conteudo, $tipo_oferta, $local); }; return $arr; then i make this in ajax (jquery) Code: [Select] data: 'all=<?php echo json_encode($arr); ?>', and in other page i make: Code: [Select] $editar = $_POST['all']; $e = json_decode($editar, true); echo $e[0][0]; the problem is: if i only do : Code: [Select] $arr[] = array($oferta); this echo $e[0][0]; outputs: designer (is the value of $oferta) but if i do Code: [Select] $arr[] = array($oferta, $cargo, $conteudo, $tipo_oferta, $local); echo $e[0][0]; simply doesn't show anything. the question is why ? and how can be solved? I have a piece of code that outputs json as you can see from the example below it add \ / in front of urls & for ' it turns it into ' is there something i can do to correct this? Code: [Select] if (mysqli_num_rows($r) > 0) { // Available. while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $results[] = array( 'blog_id' => ($row['ID']), 'post_date' => ($row['pd']), 'post_title' => ($row['post_title']), 'article_img' => ('http://www.socialnewsoffice.com/uploads/'.$row['article_img']), 'post_content' => ($row['post_content']), 'tags' => ($row['tags']), 'views' => ($row['views']), 'categorie_id' => ($row['categorie_id']), 'post_url' => ($row['post_url'])); } echo $json = Pretty_JSON(json_encode($results)); it outputs Code: [Select] [{ "blog_id":"3", "post_date":"Thu, 1 March 2012", "post_title":"Facebook's New Fan Page Learn How To Use Features", "article_img":"http:\/\/www.socialnewsoffice.com\/uploads\/17963.jpg", "post_content":"<p>This week saw the release of Facebook's latest functionality changes (Timeline for Businesses) that will shape the future of how businesses will market their campaigns, through the social media giant Facebook. A number of marketers are wondering how they will incorporate the new features in an attempt to progress and move forward with their online social media presence.<\/p>\r\n<p>Taking all the key changes in to consideration we have managed to create a guide on how to smoothly move with the times and embrace the new Facebook layout.<\/p>\r\n<p>Please read on below for helpful tips and tricks on how to excel with 'Timeline for Brands'<\/p>\r\n<h2>New Features Announced at the Facebook Marketing Conference:<\/h2>\r\n<p><strong>View and Apps:<\/strong> What was once known as Application pages has changed to 'Tabs'. These can now have customizable images linked with them and the order of them can be changed too. Below you can see from the screenshot what a customized Facebook Timeline looks like.<\/p>\r\n<p><strong>Pinning Content:<\/strong> With this new feature you can 'pin' a post to the very top of your Facebook Timeline. This is Very effective when working on a new campaign and is a great way to entice increased traffic to your tab or application page.<\/p>\r\n<p><strong>Featured 'Starred' Content:<\/strong> This feature allows you to select key content or imagery and extend it so it fits across your entire page. Therefore giving you featured content on your Facebook Timeline and making it more visible.<\/p>\r\n<p><strong>Cover Photos:<\/strong> Cover Photos are another great new feature that allow you to announce your latest campaign, welcome your following community or just simply show visitors to your timeline what you can do. There are some slight flaws with this feature though and will be addressed below.<\/p>\r\n<p><strong>Page Dimensions:<\/strong> Dimensions of application pages has now changed with the release of Facebook Timeline. If you happen to be an SML user then you have all the tools necessary to update your page on your own. If your using Involvers App Suite then those applications will be updated soon.<\/p>\r\n<p><strong>Removal of Default Landing Pages:<\/strong> The commonly used Facebook landing pages have been removed and replaced with various options to allow brands to drive content to application pages. These options allow you to use your cover photo and pinned content to attract users to your personal application pages. Despite the changes it is however still possible to link directly to application pages from ads, posts and outside of Facebook.<\/p>\r\n<h2>Getting Started with Timeline For Brand:<\/h2>\r\n<p>Firstly when accessing and logging in to your New Facebook Brand Page, you will see this admin message displayed below:<\/p>\r\n<p>When will my Page change to the latest design?<\/p>\r\n<p>To see a preview of what your new pages will look like, simply click on the green button at the top of your current pages. A second option is to wait until March 30th 2012 when all pages will be upgraded automatically.<\/p>\r\n<p>Where can I visit to learn more about how to use the new Pages?<\/p>\r\n<p><strong>There are a number of places you can visit to learn all you need to know about Pages:<\/strong><\/p>\r\n<ul>\r\n<li>To find out more about new features, download the Pages Overview guide by clicking here.<\/li>\r\n<li>If your wondering how to get started with Pages then download Facebook's full Pages Product Guide by clicking here.<\/li> \r\n<li>The Pages Learning video allows you to walk through the key features with Facebook's product experts.<\/li> \r\n<li>If you need answers to specific questions, visit Facebook's Help Centre. <\/li>\r\n<\/ul>\r\n<h2>How should I choose a cover photo for my Page?<\/h2>\r\n<p>Firstly select a unique image that represents your page. Facebook itself recommends using a photo of a popular menu item, album artwork or an image of your product being used by someone. You need to experiment with a number of different images that your audience responds positively to. \r\nFew key elements of Cover Images:\r\n<\/p>\r\n<p><strong>Each Cover image must be at least 399 pixels wide and must not contain the following:<\/strong><\/p>\r\n<ul>\r\n<li>Prices \/ Purchase information and displaying offers such as \"60% off this month\" are not permitted. Also 'Download this from our website' is not allowed.<\/li> \r\n<li>No email addresses, web addresses and any other contact information.<\/li>\r\n<li>References to clicking on or the use of Facebook interface elements such as Like or Share or any other Facebook Features.<\/li>\r\n<li>\"Tell your friends\" or \"Get it now\" or any other calls to action are not allowed in the latest version of Facebook Timeline.<\/li>\r\n<\/ul>\r\n<p>All Timeline cover imagery is public and therefore means anyone visiting your Page will be able to see exactly which image you have chosen. The photos you display must not be deceptive, false or misleading any way that infringes on third party intellectual property. You must also not encourage of incentivize other fellow users, friends or business associates to display the same cover image as yours on personal Timelines.<\/p>\r\n<p>To sum up we are extremely excited about the latest Facebook feature release this week. They constantly deliver new services that are amazing and incredibly innovative to the market place.<\/p>\r\n<p>Here at Northplanet we are commited to provide you with the latest information on the hottest online topics around, to keep you ahead in the game. We would love to hear some feedback from you on the brand new Facebook 'Timeline for Brands' release and invite you to visit our very own <a href=\"https:\/\/www.facebook.com\/northplanet\">Northplanet Facebook Timline page by clicking here.<\/a><\/p>", "tags":"facebook, new fan page", "views":"253", "categorie_id":"2", "post_url":"facebooks-new-fan-page-learn-how-to-use-features" } If i run data that has HTML entities such as ( ) though json_encode($results) it seems to produce NULL any ideas? Since there have been some debates about how to safely pass PHP values to JavaScript, I hope I can clarify a few things.
One suggestion that kept recurring was to simply run the value through json_encode() and then inject the result into a script element. The JSON-encoding is supposed to (magically?) prevent cross-site scripting vulnerabilities. And indeed it seemingly works, because naïve attacks like trying to inject a double quote will fail.
Unfortunately, this approach doesn't work at all and is fundamentally wrong for several reasons:
json_encode() was never intended to be a security function. It simply builds a JSON object from a value. And the JSON specification doesn't make any security promises either. So even if the function happens to prevent some attack, this is implementation-specific and may change at any time.
JSON doesn't know anything about HTML entities. The encoder leaves entities like " untouched, not realizing that this represents a double quote which is dangerous in a JavaScript context.
The json_encode() function is not encoding-aware, which makes it extremely fragile and unsuitable for any security purposes. Some of you may know this problem from SQL-escaping: There used to be a function called mysql_escape_string() which was based on a fixed character encoding instead of the actual encoding of the database connection. This quickly turned out to be a very bad idea, because a mismatch could render the function useless (e. g. the infamous GBK vulnerability). So back in 2002(!), the function was abandoned in favor of mysql_real_escape_string(). Well, json_encode() is like the old mysql_escape_string() and suffers from the exact same issues.
Any of those issues can be fatal and enable attackers to perform cross-site scripting, as demonstrated below.
1)
The entire “security” of json_encode() is based on side-effects. For example, the current implementation happens to escape forward slashes. But the JSON standard doesn't mandate this in any way, so this feature could be removed at any time (it can also be disabled at runtime). If it does get disabled, then your application is suddenly wide open to even the most trivial cross-site scripting attacks:
<?php header('Content-Type: text/html; charset=UTF-8'); $input = '</script><script>alert(String.fromCharCode(88, 83, 83));</script><script>'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>XSS</title> </head> <body> <script> var x = <?= json_encode($input, JSON_UNESCAPED_SLASHES) ?>; </script> </body> </html>2) In XHTML, a script element works like any other element, so HTML entities like " are replaced with their actual characters (in this case a double quote). But JSON does not recognize HTML entities, so an attacker can use them to bypass json_encode() and inject arbitrary characters: <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); $input = "";alert('XSS');""; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>XSS</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <script type="text/javascript"> var x = <?= json_encode($input) ?>; </script> </body> </html>3) json_encode() blindly assumes that the input and the output should always be UTF-8. If you happen to use a different encoding, or if an attacker manages to trigger a specific encoding, you're again left with no protection at all: <?php header('Content-Type: text/html; charset=UTF-7'); $input = '+ACIAOw-alert(+ACI-XSS+ACI)+ADsAIg-'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-7"> <title>XSS</title> </head> <body> <script> var x = <?= json_encode($input) ?>; </script> </body> </html>(This particular example only works in Internet Explorer.) I hope this makes it very clear that json_encode() is not a security feature in any way. Relying on it is conceptually wrong and simply a very bad idea. It's generally not recommended to inject code directly into a script element, because any mistake or bug will immediately lead to a cross-site scripting vulnerability. It's also very difficult to do it correctly, because there are special parsing rules and differences between the various flavors of HTML. If you try it, you're asking for trouble. So how should one pass PHP values to JavaScript? By far the most secure and robust approach is to simply use Ajax: Since Ajax cleanly separates the data from the application logic, the value can't just “leak” into a script context. This is essentially like a prepared statement. If you're into micro-optimization and cannot live with the fact that Ajax may need an extra request, there's an alternative approach by the OWASP: You can JSON-encode the data, HTML-escape the result, put the escaped content into a hidden div element and then parse it with JSON.parse(): <?php header('Content-Type: text/html; charset=UTF-8'); $input = 'bar'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>XSS</title> <style> .hidden { display: none; } </style> </head> <body> <div id="my-data" class="hidden"> <?php $json_object = json_encode(array( 'foo' => $input, )); // HTML-escape the JSON object echo htmlspecialchars($json_object, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8'); ?> </div> <script> var data = JSON.parse(document.getElementById('my-data').innerHTML); alert('The following value has been safely passed to JavaScript: ' + data.foo); </script> </body> </html> |