Fetching PHP code from table field in database - php

I have a table notifications where I have a field notification which has value:
<?php echo '.$user['name'][0].' ?>, you are <?php echo popularity(); ?>% popular today.
The output is: , you are % popular today.
It is ignoring the PHP here. I don't understand why.
Expected output is Shubham, you are 35% popular today.
Under network in inspect element the response tab with raw data shows this:
<div class="notiText">
<?php echo $user['name'][0]; ?> you are <?php echo popularity(); ?>% popular today.
</div>
What's the issue here? Why does the script does not load PHP tags from the database?
EDIT
I have tried using eval() from here Reading php code from database. However, I have to do that into the database and not in code. The new output has this eval(), you are eval()% popular today.. Still not reading.
Note: I cannot use eval() into the coding. This has to be dynamic and from database. Therefore, anyone who is thinking of suggesting eval() I need an alternative or a workaround to the situation with eval() and database.
UPDATE
Here is the sample code:
processes/notifications.php
$stmt = $pdo->prepare("SELECT notification FROM notifications");
$stmt-> execute();
$html = "<div class='notifications'>";
while($f = $stmt->fetch()){
$html .= ''.$f['notification'].'';
}
$html .= "</div>";
echo $html;
Jquery
$(".notificationsBell").on("click", function(e){
$.ajax({
type: "POST",
url: "processes/notifications.php",
data: "all",
success: function(data){
$(".loadNotifications").html(data);
}
});
});
HTML
<div class="loadNotifications"></div>
UPDATE 2
Okay so the following code is giving me the proper output.
$str = ''.$user['name'][0].', you are '.popularity().'% popular today.';
eval("\$str = \"$str\";");
echo $str;
Output: Shubham Jha, you are 100% popular today.
Now, how do I insert that string (the value of $str) into the database? In the table field what should be the format so that it gets recognized and echoed correctly. I tried this but doesn't work.
'.$user['name'][0].', you are '.popularity().'% popular today.
Returns this error:
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in E:\xampp\htdocs\newchat\processes\notifications.php(65) : eval()'d code on line 1

Try this:
while($f = $stmt->fetch()){
// STORE IN SIMPLE VARIABLES
$name = $user['name'][0];
$popularity = popularity();
$notiText = $f['notification'];
eval("\$notiText = \"$notiText\";");
$html .= ''.$notiText.'';
}
In the database use these simple variable names and avoid using quotes.
$name, you are $popularity% popular today.

Related

preg_replace of php code

I am writing an application that will look at a single record, obtain values from about 12 flags (0 or 1), look up those flags against a status table (in MySQL) and return a variable called $status_message which is in that table.
In this table I need to have hyperlinks (working fine) but also echo some variables, i.e.
You have no bids for {{$row->_item_name}}
or
View this item now by clicking here
Now I need item name and the other example to be translated into <?php echo $row->_item_name; ?>
I have tried a preg_replace with the following:
<?php
$find = array('/{{/', '/}}/');
$replace = array('<?php echo ', ' ?>');
echo preg_replace($find, $replace, $status_message);
?>
but this is not working.
Can anyone advise how I can get the desired result and 'echo' the variable in the MySQL field?
Had a brainwave. Much simpler,
instead of $row->_item_name I just put {{itemname}} in the string. I then use the following code:
<?php
$message_buyer = str_replace('{{itemname}}', $row->_item_name , $message_buyer);
echo $message_buyer;
?>
so no need to have <?php calls in the string at all.

Pass PHP array to Javascript via onClick using JSON

I am using PHP and MySQL to loop through products and generating HTML code that consists of an img tag with an onClick event that calls a Javascript function. I want to pass PHP variables via the onClick event to a Javascript function. I'm using jQuery and thought it would be a good idea to use PHP's json_encode() function and jQuery's jquery-json plugin.
My PHP code looks like this:
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a href=\"javascript:;\" onClick=\"changepic('" . htmlentities($onclick) . "')\">";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
As you can see my Javascript function is called changepic(). I've left out a bit of code that is irrelevant to this question (i.e. the database access code and deciding where the thumbnail image is).
My Javascript code is:
function changepic(productarray) {
var productid = $.evalJSON(productarray).productid;
var productdesc = $.evalJSON(productarray).description;
alert(productid);
}
I'm not really doing anything yet with the PHP variables that I'm passing to the Javascript array, I'm just trying to get it to work first! My ultimate aim is to use jQuery to insert the product description into a <div>
A sample product detail might look like this:
ProductID: 30c7508008ac7597619ad9b90a97b40f
Description: <p>Wide and Narrow Bands<br>
Set with Top-Quality Diamonds</p><p>
As you can see the description contains HTML code, as well as a newline after the <br> tag.
The HTML that is generated looks like this:
<img src="products/tn-30c7508008ac7597619ad9b90a97b40f.jpg" width="100" height="100">
When I run this I get a Javascript error:
Event thread: click
Uncaught exception: SyntaxError: JSON.parse: Unescaped control char in string: "<p>Wid
Error thrown at line 18, column 2 in changepic(productarray) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
var productid = $.evalJSON(productarray).productid;
called from line 1, column 0 in <anonymous function>(event) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
changepic('{"productid":"30c7508008ac7597619ad9b90a97b40f","description":"<p>Wide and Narrow Bands<br>\r\nSet with Top-Quality Diamonds<\/p>"}')
From what I can see I've done something wrong with encoding the JSON string. I've done some Googling and found some people that say no encoding is necessary (I tried that and the product description was taken as HTML and showed up in the page), others say to use addslashes() and some say htmlentities().
Do I need to do something in the Javascript function to decode it before I try to use it with evalJSON()?
I usually just do this,
var foo = <?php echo json_encode($foo); ?>;
and I don't really see how this can result in any sort of an "injection" attack as long as json_encode is doing its job.
I don't understand why you are getting into so much mess.. here is the solution and it works
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a id='test' href='' var='$onclick'>";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
Here is your jquery:
$(function(){
$("#test").click(function(){
var img = jQuery.parseJSON(($(this).attr("var")));
alert(img.description);
});
});
Now since you have the json object you can create div tag and put the variables inside or put the content on already existing div tag. I am sure you know what to do here.
Dins
I think I was over-complicating things, I didn't really need to use JSON at all.
I got this working by changing my PHP code to this:
$productid = $productsRow['ProductID']
$description = rawurlencode($productsRow['Description']);
echo "<a href=\"javascript:;\" onClick=\"changepic('$productid','$description')\">";
Then my Javascript looks like this:
function changepic(productid, description) {
description = decodeURIComponent(description);
alert(description);
}
This works fine so now I can continue and actually do something useful in the Javascript function.

How can I retrieve HTML/PHP code stored in a mySQL table and not have the PHP commented out?

I am storing in a mySQL table the HTML/PHP content of individual slides to be displayed on a single page.
Here is an example of HTML/PHP code stored in the mySQL table:
<p>Welcome <?php echo $userData['fname']; ?>!</p>
<p>You made it to the first slide!</p>
I retrieve the content of the slides in PHP with the following code:
<?php
$fetchedPageSlideData = mysql_query("SELECT * FROM pageSlides WHERE pageID = $pageID ORDER BY 'order' DESC") or die(mysql_error());
while ($pageSlideData = mysql_fetch_array($fetchedPageSlideData)) {
$pageSlideContent = $pageSlideData['content']; ?>
<div><?php echo $pageSlideContent; ?></div>
<?php }
?>
All of the HTML of the content displays correctly, but the PHP is inserted as follows:
<!--?php echo $userData['fname']; ?-->
So the PHP is commented out and doesn't display.
How can I retrieve the HTML/PHP code and have the PHP not commented out?
It might be a better idea to use placeholder strings in the DB data. Executing arbitrary php code from a DB can be dangerous. PHP is Evil
Look into PHP function eval(): http://php.net/manual/en/function.eval.php
Dropping in and out of the PHP interpreter makes your code rather difficult to read. Consider:
<?php
$f = mysql_query(
"SELECT *
FROM pageSlides
WHERE pageID = $pageID
ORDER BY 'order' DESC"
) or die(mysql_error());
while ($d = mysql_fetch_array($f)) {
print "<div>" . $d['content'] . "</div>\n";
}
Regardless there is no implicit nor explicit mechanism here which would inject the comment tags you've presented. However it may be the browser trying to make sense of the unescaped html code and <?php ... ?> tags.
Try:
print "<div>" . htmlentities($d['content']) . "</div>\n";
As a side note, you might consider using
print "<div>" . highlight_string($d['content']) . "</div>\n";
Or do you mean that you actually want to run the code stored in the database - if so, you're asking for a world of pain. Eval is not evil - but you really must know what you're doing to avoid getting bitten by it.

How should I escape?

its a simple logger function. I want to load an array to a DIV content:
document.getElementById('layout').innerHTML = '<?php foreach ($logs as $item) { echo str_replace(array('"',"'"), array ('"','''), $item).'<hr />'; } ?>';
because $logs can contain HTML elements, but not quotes, since they would ruin the echoing. It should be OK, but Firefox say "malformed Unicode character sequence" and it doesnt displayed. Now what?
use html entities to translate your html code into safe sequencies
I might be wrong, but it looks like you're trying to enter php code into your page using javascript. Javascript is client side, so if anything, you will get the full code, not the parsed code.
If you want the php to be run beforehand, so the actual code in your page will be a javascript that has the allready-parsed contents in it, you neet to make a string that contains the finished content AND add "'" for javascript to understand it.
This might look like this (haven't checked the foreach for you)
<?//this part is parsed before sending it to the client
$conts = "'";
foreach ($logs as $item) {
$conts .= str_replace(array('"',"'"), array ('"','''), $item);
$conts .= "<hr/>";
}
$conts .= "'";
?>
document.getElementById('layout').innerHTML = <? echo $conts ?>;

php echo doesnt print newlines

I started doing a new project in PHP / MySql . The Aim of this project is to manage articles for a magazine that i am the editor of.
So the content of the articles, i decided i would store with the "TEXT" column type of MySql
Now when i retrieve this column and print it with echo, the newlines are not there. Its all on the same line.
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
Find below, the text as it looks in the database and as it looks when it is echoed
in the databse, it is with new lines http://img413.imageshack.us/img413/4195/localhostlocalhostzxcvb.jpg
Text as it looks when echod http://img718.imageshack.us/img718/1700/sdashboardmozillafirefo.jpg
But within the database, its stored with newlines.
Has anybody else encountered this problem?
Please help me as my project depends on this :|
Whitespace in HTML is folded into a single space. Use nl2br() if you want to maintain newlines in HTML.
Have you tried
echo $txt."<br/>";
alternatively, you can put your output between <pre> tags:
echo "<pre>";
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
echo "</pre>";
btw,
echo $txt."<br/>";
may not work since it will just append newline at the end but not within $txt string
I know this isn't part of your question, but if you additionally want new lines in your HTML code but not your presentation, use double quotes with \n. This can help keep the HTML really tidy.
echo "\n";

Categories