Unexpected output 1 in json_encode - php

I have been trying to print an output using json_encode, the code is below:
<?
$lid = $_GET['last_id'];
$sql = "SELECT * FROM tbl_posts WHERE id < $lid ORDER BY id DESC LIMIT 10";
$result = mysqli_query($con,$sql);
$json = include('datam.php');
echo json_encode($json);
?>
Here is the datam.php file:
<?
$count = 0;
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$likes = $row['likes'];
$dislikes = $row['dislikes'];
$text = $row['text'];
$text = htmlspecialchars($text);
$title = substr($text, 0, 50);
$title = preg_replace('~[^\\pL\d]+~u', '-', $title);
$title = trim($title, '-');
$title = strtolower($title);
$title = preg_replace('~[^-\w]+~', '', $title);
if(empty($title)) {
$title = "no-title";
}
$cat = $row['cat'];
$cat = strtolower($cat);
$cat = str_replace(" ","-",$cat);
$ccat = str_replace("-"," ",$cat);
$ccat = ucwords($ccat);
$by = $row['uid'];
$dt = $row['date'];
$tm = $row['time'];
$time = strtotime("$dt $tm");
$nsfw = $row['nsfw'];
if ($nsfw == 1)
$isnsfw = '<span class="nsfw">NSFW</span>';
else
$isnsfw = "";
// Time Ago
// Get OP
$suser = "SELECT * FROM tbl_users WHERE id = $by";
$muser = mysqli_query($con,$suser);
$guser = mysqli_fetch_array($muser);
$byuser = $guser['user'];
$byuser = strtolower($byuser);
$byuser = str_replace(" ","-",$byuser);
$cbyuser = str_replace("-"," ",$byuser);
$cbyuser = ucwords($cbyuser);
// WhatsApp Link
$wm = preg_replace("/\n/", "%0A", $text);
if($count == 5 && $cnsfw == 0) {
include "adapp.php";
}
echo '<div class="box" id="'.$id.'"><div class="t">Posted by '.$cbyuser.' in '.$ccat.' '.ago($time).' ago</div><div class="m">'.$text.'</div><div class="m"><span class="col-3"><span class="likes">'.$likes.' Likes</span></span><span class="col-3"><span class="dislikes">'.$dislikes.' Dislikes</span></span><span class="col-3">'.$isnsfw.'</span></div><div class="b"><span class="col-5 l bbox"><img src="/img/like.png" /></span><span class="col-5 l bbox"><img src="/img/dislike.png" /></span><span class="col-5 l bbox"><img src="/img/comment.png" /></span><span class="col-5 l bbox"><a rel="nofollow" href="whatsapp://send?text=http://whatsappstatus.in/msg/'.$id.'%0A'.$wm.'"><img src="/img/whatsapp.png" /></a></span><span class="col-5 l bbox"><img src="/img/options.png" /></span></div><div class="clr"></div></div>';
$count++;
}
?>
Using this code, all the output appears as expected but, at the end of each output, there is unexpected output 1 which has no source of origin.
Every time this code executes, it gives an unexpected 1 at the end and I can't seem to find where it is coming from.
Here is the picture of sample output:
You can visit this URL to check it: http://funpd.com/messages1

When using
$json = include('datam.php');
In your datam.php you should return the value of the data you want assigning to $json rather than echoing it out. The echo in the datam.php is code which is displaying the data and the 1 is the value being assigned to $json (which is the value returned by your datam.php page).
You can test this by commenting out the echo in the sub page and you should just see the value 1 being displayed.
It may be the easiest solution looking at your code to just include this sub-page and not assign the value to $json, but you may have a reason for json encoding the return value.
Update:
To batch data up, build an array of data. At the top
$output = [];
After your echo - build an array of the results and add it to output array...
$output[] = [$id, $byuser, $cbyuser, ...];
(You will need to complete this with all of the fields you need)
And at the end
return $output;
This will pass all the data back to the calling page.

Related

How to apply php function to $_GET to get clean URLs?

I am trying to get clean URLs of localities belong to associated district where a clean url function is applied to $_GET varialble. I've two pages, 1st one is district.php who has links to associated localities using this function to generate clean URLs. Below is the code of district.php page :-
<?php
$remove[] = " ";
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
return $string;
}
include($_SERVER['DOCUMENT_ROOT'].'/database-path.php');
$district = str_replace('-',' ',$_GET['district']);
$state = str_replace('-',' ',$_GET['state']);
$sql="SELECT * FROM table_name WHERE district='$district' AND state='$state'";
$result = mysqli_query($con,$sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$district = $row['district'];
$locality = $row['locality'];
$state = $row['state'];
$iso = $row['iso'];
}
?>
On the same district page, below code is used to generate clean URLs of associated localities :-
" . $row["locality"]. "
The above code is generating URLs to all localities pages in the manner of "locality-page-url-with-decoded-id-number" on district page.
Below is the code of locality.php where I'm trying to apply same clean function to $_GET variable in order to get clean URLs
<?php
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
return $string;
}
include($_SERVER['DOCUMENT_ROOT'].'/database-path.php');
$locality = clean($_GET['locality']);
$localID = base64_decode($_GET['id']) ;
$sql="SELECT * FROM table_name WHERE locality='$locality' AND id='$localID'";
$result = mysqli_query($con,$sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$locality = $row['locality'];
$content = $row['content'];
$district = $row['district'];
$state = $row['state'];
$iso = $row['fld_iso'];
}
}
?>
htacces code :-
RewriteRule ^([^/]*)-([^/]*)$ locality.php?locality=$1&id=$2 [L]
Now the problem I'm facing is that the $locality = clean($_GET['locality']); is not working here and is returning to error 404. It is not getting cleaned values of localities. When I try the same manually after removing clean function from $_GET variable using all characters available in the field, it works fine. Is there any way that I can use ID as the main variable in order to get row values having locality's clean values in the URL of the page?
I finally fixed it by working around the code.
Here is the new htaccess code making first parameter optional and picking ID as the main parameter to work properly:-
RewriteRule ^(.*)-([^/]*)$ locality.php?locality=$1&id=$2 [L]
Changes done on locality.php
Minor changes are done to use ID to fetch the rows in the following manner :-
<?php
include($_SERVER['DOCUMENT_ROOT'].'/database-path.php');
$localID = base64_decode($_GET['id']) ;
$sql="SELECT * FROM table_name WHERE id='$localID'";
$result = mysqli_query($con,$sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$locality = $row['locality'];
$content = $row['content'];
$district = $row['district'];
$state = $row['state'];
$iso = $row['fld_iso'];
}
}
?>
Thank you everyone for your help.

Using Preg_replace with Json

So I have attempted to get anything with a #texthere t change to a link so i can navigate them to the hash page of that specific hash.
With the code I have I just keep getting 'undefined' back. Can someone please take a look and point out where I am going wrong.
$json = array(
'userpost' => array()
);
$row = mysqli_fetch_assoc($check1);
$posts = array();
$posts['num'] = $num;
$posts['streamitem_id'] = $row['streamitem_id'];
$autoembed = new AutoEmbed();
$posts['streamitem_content'] = $autoembed->parse($row['streamitem_content']);
$regex = "/#(\w+)/";
$string=$row['streamitem_content'];
$string = preg_replace($regex, '$1', $string);
$posts['streamitem_content']=json_decode($string);
$posts['streamitem_creator'] = $row['streamitem_creator'];
$posts['streamitem_timestamp'] = $row['streamitem_timestamp'];
$posts['username'] = $row['username'];
$posts['id'] = $row['id'];
$posts['first'] = $row['first'];
$posts['middle'] = $row['middle'];
$posts['last'] = $row['last'];
$json['userpost'][] = $posts;
echo json_encode($json);
Okay this is what I've done to fix the issue. no decoding needed and that is what was causing the issue.
$regex = "/#(\w+)/";
$posts['streamitem_content'] = $row['streamitem_content'];
$posts['streamitem_content'] = preg_replace($regex, "
<a href='hash.php?tag=$1'>$1</a>", $posts['streamitem_content'] );

Escape HTML entities in JSON

My JSON result http://daysof.me/lowyat/list.php
What I did:
$num = 0;
$array = array();
foreach($rows as $go){
if($num == count($rows)-1){break;}
$reply = $go->find('td',3)->plaintext;//replies
$starter = $go->find('td',4)->plaintext;//starter
$views = $go->find('td',5)->plaintext;//views
$action = $go->find('td',6)->plaintext;//last action
$desc = $go->find('td',2)->find('div div',2)->plaintext;//description
$title = $go->find('td',2)->find('div div a',0)->plaintext;//topic name
$link = $go->find('td',2)->find('div div a',0)->href;
$array[]= array(
'title'=>$title,
'desc'=>$desc,
'starter'=>trim($starter),
'replies'=>trim($reply),
'url'=>'https://forum.lowyat.net'.$link
);
$num ++;
}
echo json_encode($array);
You'll see some single quote been turned into " and ampersand gave strange code.
How can I escape that? I tried 'title'=>htmlentities($title) still no luck with that.

Undefined error in accessing results from url

I'm making ajax call to search movies using the imdb api and I noticed for queries with spaces I get error; Undefined variable: id in C:\wamp\www\.. for some of the results. How can I fix this?
($row = mysql_fetch_assoc($sql));
$id = $row['imdb_id'];
$test = "http://imdbapi.org/?id=tt00".$id."&type=json&plot=simple&episode=1&lang=en-US&aka=simple&release=simple&business=0&tech=0";
$cont = file_get_contents ($test);
$data = json_decode($cont, true);
$title = $data['title'];
echo "$title";
This code is fairly working for me, (tested at my local server)
<?php
$row = array('imdb_id'=> 4);
//print_r($row);
$id = $row['imdb_id'];
$test = "http://imdbapi.org/?id=tt00".$id."&type=json&plot=simple&episode=1&lang=en-US&aka=simple&release=simple&business=0&tech=0";
$cont = file_get_contents ($test);
$data = json_decode($cont, true);
$title = $data['title'];
echo "$title";
Output - Un bon bock
Remove ( and ) [Thanks to Marcel] from this line -
($row = mysql_fetch_assoc($sql));
To $row = mysql_fetch_assoc($sql);

php banner rotater problem

i want to create dynamic banner rotater wih php ajax i want to pass the mysql_fetch_array() to an array to create a new array() to create xml response..........
here is my code
$sql = mysql_query("SELECT * FROM ads");
header('Content-type: text/xml');
echo '<?xml version="1.0" ?>';
while($row = mysql_fetch_array($sql)){
$title = $row['title'];
$img = $row['file'];
$body = $row['body'];
$ban = '<b>'.$title.'</b><br><br><img src="ads/'.$img.'"><br><br>'.$body;
$banners = array(
$ban,
);
$html = $banners[array_rand($banners)];
}
<banner>
<content><?php echo htmlentities($html); ?></content>
<reload>3000</reload>
</banner>
but it is return only one ad not return multiple ads how can i fix that
The proble is here: $banners = array($ban);. What you're trying to do is include all the ads in the $banners array as an entry but you are failing to achieve that.
The correct code for including an entry in an array would be $banner[] = $ban. That way each ad that comes as a result from your query will be stored as an individual entry.
So the correct code would be:
$sql = mysql_query("SELECT * FROM ads");
$banner = array(); //Define the array before trying to add elements.
header('Content-type: text/xml');
while($row = mysql_fetch_array($sql))
{
$title = $row['title'];
$img = $row['file'];
$body = $row['body'];
$ban = '<b>'.$title.'</b><br><br><img src="ads/'.$img.'"><br><br>'.$body;
$banner[] = $ban; //Adding a new entry at the end.
$html = array_rand($banner); //Getting a random entry.
}
Use this in the while loop:
$banners[] = $ban
Instead of
$banners = array(
$ban,
);
and
$html = array_rand($banners);
instead of
$html = $banners[array_rand($banners)];
And to what bzabhi said, define your
$banners = array();
before the while loop, and the randomization part has to go after the loop.

Categories