PHP function problem - php

My PHP function for sidebar element generation looks like that
function makeSidebarEl ($side, $name, $lang, $db)
{
$title='title_'.$lang;
$txt='txt_'.$lang;
$query=$db->query("SELECT $title, $txt FROM sidebar WHERE side='$side' AND name='$name'");
$result=$query->fetch_array(MYSQLI_BOTH);
$title=makeTitle($result[$title], $lang, $db);
$txt=makeTxt($result[$txt], $lang, $db);
echo '<div class="nav">'.$title.$txt.'</div>'."\n";
}
But i'm getting result something like this
<div class="nav"></div>
<div class="nav_1"><img border="0" src=core/design/img/left_nav.png alt="" height="25px"/></div>
...
I mean it opens and closes <div class="nav"></div> at the begining of the every element but in fact function must echo result within this div:
echo '<div class="nav">'.$title.$text.'</div>'."\n"; How to fix that problem?
UPDATE
function makeTitle($title) {
echo '<div class="nav_1"><img border="0" src=core/design/img/left_nav.png alt="" height="25px"/></div>
<div class="nav_2">'.$title.'</div>
<div class="nav_3"><img border="0" src=core/design/img/left_nav.png alt="" height="25px"/></div>
<div style="clear:both;"></div>';
}
function makeTxt($txt) {
echo '<div id="parts" class="parts_txt">'.$txt.'</div>';
}

makeTitle() and makeText() should return strings rather than echo them.
As it is now, they echo text when they are called and return NULL, which is then concatenated into string when you call echo '<div class="nav">'.$title.$txt.'</div>'."\n";, i.e., that line evaluates to echo '<div class="nav">'.NULL.NULL.'</div>'."\n";

You need to replace echo to return at functions makeTitle and makeTxt

Related

what is wrong with this piece of code? html + php

i've a simple function, which has two parameters, one for the image url, and other for the attributes for the image
function image_found($url,$attributes)
{
if(#getimagesize($url))
{
echo '<img src="'.$url.'" '.$attributes.'/>';
}
else
{
echo '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>';
}
}
now what i'm trying to do is create a clickable image, if the image is found, now this is the html code
echo '<div class="panel-body">';
echo '<div class="col-md-12 col-lg-12 col-sm-12 text-center">';
$url = base_url().'product_images/'.$result->product_image.'.'.$result->image_type;
$attributes = 'height="200px" width="100%"';
echo ''.image_found($url,$attributes).'';
echo '</div>';
echo '</div>';
and this is the output i'm getting
<div class="panel-body">
<div class="col-md-12 col-lg-12 col-sm-12 text-center">
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
</div>
</div>
i don't know what is wrong here, i'm using bootstrap
Just use return statements instead of echo in your function and your problem should be solved ;-)
The better way is verify if your image exists (remove #) and then return (instead of echo):
...
if(file_exists('your/path/to/image'))
return '<img src="'.$url.'" '.$attributes.'/>';
else
return '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>'
...
When you need to return a value from a function, use return statement instead of echo
When echo is used the output immediately gets printed instead of getting returned to the place where the function call is. Here is an illustration.
function printer(){
echo 'second';
}
echo 'first'.' '.printer().' '.'last';
The Output:
secondfirst last
This is the exact same thing happening with your code. The echo in image_found() gets printed as
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
The rest of the echo statement gets printed as
So using a return statement should solve your problem

PHP Code is printing text not typed code

I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);

Nesting HTML/PHP statement inside another PHP statement

I have an IF/ELSE statement and I would like to print out some images that I am getting from my Drupal site. I can't figure out how to print those IMG tags without getting errors.
This is what I have so far:
<?php
$field = field_get_items('node', $node, 'field_visitor_image');
if($field){
<img src="<?php print image_style_url('lead_teaser', $node->field_visitor_image['und'][0]['uri']); ?>">
}
else
{
<img src="<?php print image_style_url('lead_teaser', $node->field_banner_image['und'][0]['uri']); ?>">
}
?>
You have to break out of PHP mode when you start outputting HTML.
if($field){
?>
<img src="<?php print image_style_url('lead_teaser', $node->field_visitor_image['und'][0]['uri']); ?>">
<?php
}
Use echo and string concatenation:
if ($field) {
echo '<img src="' . image_style_url('lead_teaser', $node->field_visitor_image['und'][0]['uri']) . '">';
}
You cannot nest
<?php > inside another <?php >.
One option for you could be to concatenate using ".".

getting variable from while loop

Okay, I think what I've got is pretty simple for an experienced web dev person. Right now, this this is the index page for State of Debate, my debate website. From the code below, you can see that I have a while loop to echo out each debate, which corresponds to a "did" in the mySQL database. What I need to do, for upvote/downvote purposes, is to get each "did" that goes through the loop. I would then pass it to the "upvote.php" and "downvote.php".
I've tried a foreach loop, although that could be the answer and I just didn't find it. I've used $_SESSION['did'] = $row['did'] and all that does is pass the last did to the PHP page.
Any help is appreciated. And please ask if you need more info.
<?php
$result = mysql_query("SELECT did,debatetitle FROM debates");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><a href='/debatepage.php?did=" . $row['did'] . " '>" . $row['debatetitle'] . "</a></td>";
?>
<tr><td>
<a href="upvote.php" onClick="alert('You have given this item a thumbs up! You can change your vote, or leave it how it is.')"; onMouseOver="return changImage()" onMouseOut= "return changImageBack()" ><img
name="jsbutton2" src="Graphics/thumbs-up-unclicked.jpeg" width="75" height="75" border="0"
alt="javascript button"></a>
<script type="text/javascript">
function changImage()
{
document.images["jsbutton2"].src= "Graphics/thumbs-up.jpeg";
return true;
}
function changImageBack()
{
document.images["jsbutton2"].src = "Graphics/thumbs-up-unclicked.jpeg";
return true;
}
</script>
<a href="downvote.php" onClick="alert('You have given this item a thumbs down! You can change your vote, or leave it how it is.')"; onMouseOver="return changeImage()" onMouseOut= "return changeImageBack()" ><img
name="jsbutton1" src="Graphics/thumbs-down-unclicked.jpeg" width="75" height="75" border="0"
alt="javascript button"></a>
<script type="text/javascript">
function changeImage()
{
document.images["jsbutton1"].src= "Graphics/thumbs-down.jpeg";
return true;
}
function changeImageBack()
{
document.images["jsbutton1"].src = "Graphics/thumbs-down-unclicked.jpeg";
return true;
}
</script>
</tr></td>
<?php
echo "</tr>";
}
echo "</table>";
change this:
<a href="upvote.php" onCli....
to
<a href="upvote.php?did<?PHP echo $row['did']"; ?> onCli
and the same with downvote link.
To use the variable in upvote.php:
<?PHP
echo $_GET['did'];
?>

passing arguments to zend partial and zend partialLoop

I'll try to describe this as best as possible, i haven't encountered this problem before but maybe i'm doing something wrong.
In my controller: i have:
public function indexAction() {
$this->view->projects = $this->projects->getProjects();
}
In the view file corresponding to this controller i have:
<?php echo $this->partial('partials/sidebar/_home.phtml', array($this->projects)); ?>
My _home.phtml contains the current code:
<div class="sidebar-content">
<p class="sidebar-title">Projects Portfolio</p>
<div id='coin-slider' style="margin:0 auto;">
<?php echo $this->partialLoop('partials/sidebar/_projects-slideshow.phtml', $this->projects);?>
</div>
</div>
And my _projects-slideshow.phtml has this code:
<a href="<?php echo $this->baseUrl($this->pimage); ?>">
<img src="<?php echo $this->baseUrl($this->pimage); ?>" alt="1" />
<span>
<?php echo $this->pname . ' by ' . $this->group . '. Client: ' . $this->client; ?>
</span>
</a>
The problem is that the variable is not passed to _home.phtml. I tried a Zend_Debug::dump($this->projects) and the result was NULL. I tried a Zend_Debug::dump($this) and I found the projects array. What am I doing wrong? The variable is not being passed, or maybe it is, to _home.phtml, not to mention that _projects-slideshow.phtml has no idea what $this->projects is.
If $this->projects in your _home.phtml is empty I think you should change
in index.phtml
<?php echo $this->partial('partials/sidebar/_home.phtml', array($this->projects)); ?>
into
<?php echo $this->partial('partials/sidebar/_home.phtml', array('projects' => $this->projects)); ?>
Here how it should has been:
$variables = array (
'records' => $result
);
$this->view->partial ("nodes/relations.php", $variables);
The variables in the array are named. What exactly is in your $this->projects->getProjects() ?

Categories