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

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.

Related

Unexpected output 1 in json_encode

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.

find and replace all occurrences of string [php shortcodes]

i'm using this code to replace shortcodes in a CMS with links including images but it replaces only the first shortcode
$string = $row['Content'];
if(stristr($string,'[gal=')){
$startTag = "[gal=";
$endTag = "]";
$pos1 = strpos($string, $startTag) + strlen($startTag);
$pos2 = strpos($string, $endTag);
$gal = substr($string, $pos1, $pos2-$pos1);
$q=$db->prepare("select * from images where Gal_ID = :gal");
$q->execute(["gal"=>$gal]);
$imgs='';
while($r=$q->fetch(PDO::FETCH_ASSOC)){
$images[] = $r['Image'];
}
foreach($images as $val){
$imgs .= "<a href='gallery/large/$val' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/$val'></a>";
}
$result = substr_replace($string, $imgs, $pos1, $pos2-$pos1);
$result = str_replace($startTag,'',$result);
$result = str_replace($endTag,'',$result);
echo $result;
}
else{
echo $string;
}
string contains some paragraphs and 2 shortcodes
[gal=36] and [gal=37]
the result is replacing only the first shortcode with links and images but the second shortcode is displayed like this: "37" just the number. So how to loop through all shortcodes to replace them with links not only the first shortcode
Here is a full example how I described above.
//get matches
if(preg_match_all('/\[gal=(\d+)\]/i', $string, $matches) > 0){
//query for all images. You could/should bind this, but since the expression
//matches only numbers, it is technically not possible to inject anything.
//However best practices are going to be "always bind".
$q=$db->prepare("select Gal_ID, Image from images where Gal_ID in (".implode(',', $matches[1]).")");
$q->execute();
//format the images into an array
$images = array();
while($r=$q->fetch(PDO::FETCH_ASSOC)){
$images[$r['Gal_ID']][] = "<a href='gallery/large/{$r['Image']}' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/{$r['Image']}'></a>";
}
//replace shortcode with images
$result = preg_replace_callback('/\[gal=(\d+)\]/i', function($match) use ($images){
if(isset($images[$match[1]])){
return implode('', $images[$match[1]]);
} else {
return $match[0];
}
}, $string);
echo $result;
}
I tested it as much as I could, but I don't have PDO and/or your tables. This should work as a pretty much drop in replacement for what you have above.

PHP Replace Emoticon from MySQL Can't looping

I have some problem with my syntax coding about emoticon.
it can replaced as well in first post, but in next post it can't replaced.
it not looping as well.
you can see the images in:
http://postimg.org/image/srph22j8d/
# POPULATED EMOTICON
$sqlEMO = "SELECT * FROM apprtcfg WHERE obj_typ = 'EMO' ORDER BY id ASC;";
$queryEMO = mysql_query($sqlEMO);
while ($rsltEmo=mysql_fetch_array($queryEMO)) {
$emo_code = $rsltEmo['obj_link'];
$emo_img = $rsltEmo['obj_source'];
}
echo $content = str_replace($emo_code,'<img src="image/'.$emo_img.'">', $row['content']);
You should replace your emotions with images, inside while and echo it after end of while.
$sqlEMO = "SELECT * FROM apprtcfg WHERE obj_typ = 'EMO' ORDER BY id ASC;";
$queryEMO = mysql_query($sqlEMO);
$content = $row['content'];
while ($rsltEmo=mysql_fetch_array($queryEMO)) {
$emo_code = $rsltEmo['obj_link'];
$emo_img = $rsltEmo['obj_source'];
$content = str_replace($emo_code,'<img src="image/'.$emo_img.'">', $content);
}
echo $content;

Regular Expression From MySQL

I have a table in MySQL that contains couple of expressions that I want to pass to preg_replace
My code:
$q = mysql_query("SELECT * FROM TABLE");
while($r=mysql_query($q)) {
$expressions = $r['expressions'];
}
$expressions = explode("\n", $expressions);
foreach ($expressions as $expression) {
$content = preg_replace($expression, '', $content);
}
Some data in database:
#<div class="FBTbtn">(.*?)</div>#
#<!-- Extra Link -->(.*?)<!-- End Of Extra Link -->#
#<a(.*?)/a>#
#Learn More:#
As described on the mysql_query() function page, iterate through the results with mysql_fetch_assoc(). http://php.net/manual/en/function.mysql-query.php
$content = 'foo bar baz';
$result = mysql_query("SELECT * FROM expressions");
while ($row = mysql_fetch_assoc($result)) {
$content = preg_replace($row['expression'], '', $content);
}
By the way, mysql_*() functions are deprecated. You should switch to PDO.
http://php.net/manual/en/book.pdo.php
I fixed the it by using "," instead of "\n"
Code:
$q = mysql_query("SELECT * FROM TABLE");
while($r=mysql_query($q)) {
//Remove last "," from string
$expressions = rtrim($r['expressions'], ",");
}
//Explode string into array based on "," instead of "\n"
$expressions = explode(",", $expressions);
foreach ($expressions as $expression) {
$content = preg_replace($expression, '', $content);
}
Data in database should look like:
#<div class="FBTbtn">(.*?)</div>#,#<!-- Extra Link -->(.*?)<!-- End Of Extra Link -->#,#<a(.*?)/a>#,#Learn More:#,

MySQL slashes and nl2br

I am trying to store HTML posted from a textarea into a database. I have a textarea inside a form which I have called "message". The PHP code that processes it is:
if(isset($_POST['submit'])){
if(isset($_POST['title']) && isset($_POST['message'])){
$title = $_POST['title'];
$message = $_POST['message'];
if(get_magic_quotes_gpc()){
$title = stripslashes($title);
$message = stripslashes($message);
}
$title = mysql_real_escape_string($title);
$message = mysql_real_escape_string($message);
$q = "INSERT INTO table (title,datetime,text) VALUES ('{$title}',NOW(),'{$message}')";
$rows_affected = $db->exec($q);
if($rows_affected > 0){
echo "<p>Done.</p>";
} else {
echo "<p>Failed. </p>";
}
}
}
The problem I am having is then retrieving this and converting newlines to <br />. Here is what I am doing:
$res = array();
$order = array("\r\n","\n","\r");
$replace = '<br />';
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as $result){
$result['title'] = stripslashes($result['title']);
$result['text'] = str_replace($order, $replace, stripslashes($result['text']));
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I just can't get rid of those pesky \r\n's in the message. I have tried changing $order to
$order = array("\\r\\n","\\n","\\r");
// and even
$order = array("\\\r\\\n","\\\n","\\\r");
but nothing seems to work. Any ideas?
if ($res = $db->get_all('SELECT title,datetime,text FROM table')){
foreach ($res as &$result){
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I did three things:
Remove the stripslashes. They mustn't be there. The slashes mysql_real_escape_string adds are removed when the query is executed.
I used the function nl2br for the new lines. Why write something yourself if it's already built in?
I added a & in front of $result in the foreach loop. If I didn't do this only the shallow copies were modified, not the variables themselves. Thus there wouldn't be any change at all.
For the retrieving of the data you don't need to screw around with str_replace/stripslashes.
$res = array();
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as &$result){
$result['title'] = $result['title']; // Don't see the reason for stripslashes here
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
Use nl2br to convert your \n to proper HTML line breaks. (Note: If you want to show the text inside of a textarea again, e.g. for editing, you need to output the "text" as-is). The only thing that you would want to do is use strip_tags to prevent HTML from being inserted into your output.
more usual way of what nikic did
foreach ($data as $key => $row){
$data[$key]['text'] = nl2br($row['text']);
}
you did overwrite your temporary $result variable, while you have to write modified variable back into array.
and give our variables sensible names.
Also, consider to use htmlspecialchars() if it's user supplied text.

Categories