I currently have the following code coming from a database table:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
<?php
$friends = $user->getFriends();
?>
<p class="widgetContent">
<?php
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
?>
<span class="friendImage" style="text-align:center;">
<?php print $friend->username; ?>
</span>
<?php
}
?>
</p>
</div>
Now, ive tried using the eval function in php but i get a parse error unexpected '<'. I've also tried using the output buffer method (ob_start) without success too. Any ideas as to how i can get this code to evaluate without giving me an error?
note: the database code is stored in a variable called $row['code'].
The PHP eval function expects PHP code to execute as it's parameter, not HTML. Try enclosing your DB values with PHP close and open tags:
eval('?>' . $row['code'] . '<?php');
eval = evil!
Especially if the eval'd code comes from a db... one mysql injection = full php execution = full control.
Rather use some placeholders and replace them (like any other good templating system does).
You could store this in your database:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
{%friendstemplate%}
</div>
Then str_replace the placeholders with the content they should have. In your example i would also add a subtemplate per friend like this:
<span class="friendImage" style="text-align:center;">
{%username%}
</span>
... which you could loop and insert into {%friendstemplate%}.
You cant use eval on markup code. Either save the code to a temporary file so that you can include it, or rewrite the code so that it's not markup, something like:
print "<h1 class=\"widgetHeader\">My Friends</h1>";
print "<div class=\"widgetRepeater\">";
print "<p class=\"widgetHeader\">Random Selection</p>";
$friends = $user->getFriends();
print "<p class=\"widgetContent\">";
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
print "<span class=\"friendImage\" style=\"text-align:center;\">";
print $friend->username;
print "</span>";
}
print "</p>";
print "</div>";
Related
So I have tried researching this before jumping into asking this question. Given that I have an index.php, and a cookie which stores the username, saved as $name, most answers tell me its simple to do this:
echo '<h3>'.$name.'</h3>'
But this doesnt work for me, and I assume its because im doing strange syntax for an if statement first, and I want to use the parameter within this if statement. My exact code looks more like this:
<?php
//store the cookie
$name=$_COOKIE['user'];
//check that it is set
if(isset($_COOKIE['user'])):
<section id="login">
<h1> Welcome</h1>
echo '<h3>'.$name.'</h3>';
</section>
else: //prompt to login
endif;
?>
It is meant to show a welcome message to a user that is logged in, adressing them by name, otherwise prompt the user to login.
So my question is: Why doesn't the parameter reflect at all? (shows nothing when the page is loaded) and How can I get this to work as intended?
ps. Please don't worry about the security risk of using cookies to do this etc. It is purposefully vulnerable.
pps. I am 100% sure the cookie is set, I viewed it with a cookie browser.
It doesn't work because the previous two lines are invalid PHP so it would throw an error and stop working.
If you want to use the echo approach then the correct syntax would be:
echo '<section id="login">';
echo '<h1> Welcome</h1>';
echo '<h3>'.$name.'</h3>';
It is important to never insert external data as if it were raw HTML. This can render you vulnerable to XSS attacks. Treat the input as plain text and convert it to HTML before outputting it into an HTML document.
$name_html = htmlspecialchars($name);
echo '<section id="login">';
echo '<h1> Welcome</h1>';
echo '<h3>'.$name_html.'</h3>';
You can make the code easier to read by using variable interpolation:
$name_html = htmlspecialchars($name);
echo '<section id="login">';
echo '<h1> Welcome</h1>';
echo "<h3>$name_html</h3>";
And when outputting large chunks of HTML, it is easier to just drop out of PHP mode entirely:
$name_html = htmlspecialchars($name);
?>
<section id="login">
<h1> Welcome</h1>
<h3><?=$name_html?></h3>
<?php
Aside
Check to see if the cookie is set before you try to use it, not afterwards!
if(isset($_COOKIE['user'])):
$name=$_COOKIE['user'];
you should use php + html like this:
<?php $var = 'my string'; ?>
<?php if ($var == 'my string') : ?>
<h1><?php echo $var; ?></h1>
<?php endif;?>
this breaks up the if statement, allowing you to add html inbetween the conditional statement without having to echo and html from php
You should post any errors you get - But your can't just write html inside php, without either echoing it out, or ending the php for a while.
<?php
//store the cookie
$name=$_COOKIE['user'];
//check that it is set
if(isset($_COOKIE['user'])):?>
<section id="login">
<h1> Welcome</h1>
<?php echo '<h3>'.$name.'</h3>'; ?>
</section>
<?php else: //prompt to login
endif;
?>
To display HTML code only if a php statement is true, just close the php tag right after you have opened the if statement and then put your HTML code between.
<?php
//store the cookie
$name=$_COOKIE['user'];
//check that it is set
if(isset($_COOKIE['user'])) {
?>
<section id="login">
<h1> Welcome</h1>
<h3><?php echo $name; ?></h3>
</section>
<?php
} else {
echo 'Please login';
}
?>
Here is my variable that I am actually getting from my MySQL Database:
<h1>This is a H1</h1>
<p>NOT BOLD</p>
<p> </p>
<p><strong>BOLD</strong></p>
I am using TinyMCE to format the code.
Here is how I echo it
<?php
// WHILE LOOP GETTING $ROW FROM MYSQL
$conContent = $row['content'];
Then, when I go to the page, it displays the output like this...
http://i.snag.gy/BbMqx.jpg
I want the variable to make the echo formatted. So like then it will have all the html formatting.
You can insert your variable inside the <strong> tags using the following method:
<?php
/* getting row from your table */
$conContent = $row['content'];
?>
<strong> <?php echo $conContent; ?> </strong>
Another solution is:
$conContent = $row['content'];
echo "<strong>" . $conContent . "</strong";
//or echo "<strong> $conContent </strong";
If the styles are to be applied to all the rows, then you could use a foreach loop:
foreach($row as $v) {
echo "<strong>$v</strong";
}
Note: This assumes that you've the mysql array result stored in a variable called $row.
It's not just for <strong tags. You can use <h1>, <p>, <div> -- it doesn't matter. PHP will output the variable content in the location you specify.
Hope this helps!
Can you check the HTML source of the output? Is the HTML still around? It looks like strip_tags() or HTMLPurifier removes your HTML. Otherwise you would either see the formatting applied or the tags in the output.
If you have HTML code in your database you don't have to do anything with it in PHP, but can directly print it.
<div class="interactionLinksDiv">
REPLY
</div>
I have call the javascript function toggleReplyBox with five parameters. This code is written inside the php tags. But this code is not executing properly and the parameters are not being passed properly. If I call the function toggleReplyBox here with no parameters it works fine but thats not what I want.
<div class="interactionLinksDiv">
REPLY
</div>
When I copied this code to the html part of my php file It works fine and the parameters are passed and the function executes properly.
But I want to know why the function is not able to work inside of the php tags when everything is the same.
function toggleReplyBox(sendername,senderid,recName,recID,replyWipit) {
$("#recipientShow").text(recName);
document.replyForm.pm_sender_name.value = sendername;
document.replyForm.pmWipit.value = replyWipit;
document.replyForm.pm_sender_id.value = senderid;
document.replyForm.pm_rec_name.value = recName;
document.replyForm.pm_rec_id.value = recID;
document.replyForm.replyBtn.value = "Send";
if ($('#replyBox').is(":hidden")) {
$('#replyBox').fadeIn(1000);
} else {
$('#replyBox').hide();
}
}
Inside the php tags I changed the code :
print <<<HTML
<div class="interactionLinksDiv">
REPLY
</div>
HTML;
And it is still showing the error
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\Fluid Solution\fluid-solution-website-template\interact\profile1.php on line 130
Line 130 is the <a href... line.
The first version of your code is neither PHP (javascript/HTML tags are "naked") nor Javascript: the "." string concatenation operator won't work in Javascript, nor will the $variable expansion.
You can get it to work in PHP like this:
<?php
$fullname = "Test";
$current_id = 15;
$id = 9;
$thisRandNum = 42;
// All lines beyond this point, and...
print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id',
'$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;
// ...up to here, start at the first column (i.e. they are not indented).
?>
Note that within the here-document (area between <<<HTML and HTML), you can't use the string concatenation operator "." (or any other).
Or you can do as you did in the second version of your code, replacing only the variables with <?php echo $variablename; ?> and leaving all the rest as HTML.
As a simpler example let's consider an alert() box with message sent from PHP. This means that:
1) the script is executed server side; anything between <?php ?> tags is executed, and its output replaces the tags themselves.
After this phase, we no longer have PHP but a mix of HTML and Javascript, which can be executed by the client it's sent to. So we want to have a HTML like
<script type="text/javascript">
alert('Hello, world');
</script>
To do this we can generate all the HTML in PHP:
echo '<script type="text/javascript">';
echo "alert('$message');"; // or also: echo 'alert("' . $message . '");';
echo '</script>';
Or we can do it with a here-document, where operators do not work, but $variables do:
echo <<<HEREDOCUMENT
<script type="text/javascript">
alert('$message');
</script>
HEREDOCUMENT;
Or we can run it all in HTML, and only rely on PHP to generate the lone variable:
<script type="text/javascript">
alert('<?php echo $message; ?>');
</script>
But always you need to keep separated what it's being done in PHP, what in Javascript, and what is in the HTML markup.
The following code is for a Wordpress plugin, it displays points and tank of a user:
<?php
if(function_exists('cp_displayPoints') && $authordata->ID){
echo '<span class="cubepoints_buddypress">'; cp_displayPoints($authordata->ID); echo '</span>';
if(function_exists('cp_module_ranks_getRank')) echo ' <span class="cupepoints_buddypress_rank">'.cp_module_ranks_getRank($authordata->ID).'</span>';
}
?>
I am trying to extract these two echo functions from the If statement but only succeeded with one of them. I can echo the points like this:
<?php cp_displayPoints($authordata->ID); ?>
Works fine. Now I tried doing the same with the second echo:
<?php cp_module_ranks_getRank($authordata->ID); ?>
But it did not work. Obviously, there is some basic thing that I am missing here. Do you know what it is?
The first one likely prints directly to output, while the second returns its value. So, you need to echo() the second one, just as they're doing in your sample code:
<?php echo cp_module_ranks_getRank($authordata->ID); ?>
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.