views:

50

answers:

3

Hi there, I'm attempting to return a string of html with an some php code within the html and I'm experiencing a bit of difficulty doing so. Example below:

return '//bunch of html here
<div id="test">
 <?php 
   if (isset($_COOKIE[\"cannycookie\"]))
   {
      echo "<a class=\"reply\" href=\"#\" id=\"deletelink-'.$d['id'].'\">Delete</a>";
   }
 ?>
</div>';

The html before this all returns perfectly, but when it gets to the ">Delete</a>";}?> something crashes and burns. The html renders in the browser like so: Delete\n"; } ?> with the whole php source being exposed. I've tried reading up other posts and information on quotes in statements as such, and I've tried as much as I can, yet to no avail. Any ideers? Thanks!

+2  A: 

php inside php is strange, try this:

if (isset($_COOKIE["cannycookie"]))
{
    return '<div id="test">
              <a class="reply" href="#" id="deletelink-'.$d['id'].'">Delete</a>
            </div>';
}
else
{
    return '<div id="test"></div>';
}
charles.art.br
The thing is, I'm calling the function in a different php file that returns this html code (specifically user comments) and when the correct user is logged in, it adds the delete button. Not sure what to do.
Ryan
A: 

Do not return like that for sanity purposes, instead:

$myReturnStatement = htmlentities('whatever you wanted');
return $myReturnStatement;

On the receiving end, you strip slashes and decode the entities back into legitimate PHP code. Also, if I understand my quotes correctly, you can have double quotes inside of single quotes without having to slash them out. This should save you headache. Once the code is decoded into normal PHP code, just use eval() to evaluate as PHP.

http://us2.php.net/manual/en/function.stripslashes.php
http://php.net/manual/en/function.htmlentities.php
http://www.php.net/manual/en/function.html-entity-decode.php
http://php.net/manual/en/function.eval.php

lighthazard
Just tried this, it seems to just be rendering all the html source visibly on the page.
Ryan
You'll have to decode the entities and then use eval().http://php.net/manual/en/function.eval.php
lighthazard
A: 

Don't return PHP. It won't work, and even if it did, using eval() et al is considered to be harmful (and a serious security issue) except in very specific circumstances.

Try this:

<?php

$retval = '<div id="test"> <!-- whatever you need here -->';
if (isset($_COOKIE["cannycookie"]))
{
  $retval .= '<a class="reply" href="#" id="deletelink-'.$d['id'].'">Delete</a>';
}

return $retval;

?>
Spoom