Adding a $var intro a $var - php

I am newbie in php, but I need to modify some string in order to add a link with rel intro a visual composer shortcode, an animated icon.
The problem is that I have this variable, by default where i should add two variables only if insered.
Here is the originary code:
$svg_icon = '<div class="svg-icon-holder" data-size="'. $icon_size . '" data-animation-speed="'.$animation_speed_time.'" data-animation="'.$enable_animation.'" data-animation-delay="'.$animation_delay.'" data-color="'.strtolower($color) .'"><span>'. get_template_directory_uri() . '/css/fonts/svg/' . $image .'</span></div>';
The problem is that: I should insert a before the tag <div> into the code and a after the closing div BUT this only if variable &icon_link is set, if not, the <a> tag should not appear as I do not need to have a link to all icons.
Hope I have explained myself well, if not let me know!
Regards, Alin.

Do an if-statement, if $icon_link is defined and set, then add your <a> tag to your $svg_icon variable using a dot(.):
$svg_icon = '<div class="svg-icon-holder" data-size="'. $icon_size . '" data-animation-speed="'.$animation_speed_time.'" data-animation="'.$enable_animation.'" data-animation-delay="'.$animation_delay.'" data-color="'.strtolower($color) .'"><span>'. get_template_directory_uri() . '/css/fonts/svg/' . $image .'</span></div>';
if($icon_link)
{
$svg_icon = '<a href="'. $icon_link . '" rel="'. $icon_link_rel .'">'.
$svg_icon.'</a>';
}

Just use a if statment. You are manipulating string, so you can easily add words to an other string like that
if ($icon_link){
$beginning = "<a href='$icon_link' rel='$icon_link_rel'>";
$ending = "</a>"
}
else {
$beginning = "";
$ending = ""
}
$svg_icon = "$beginning<div class='svg-icon-holder' data-size='$icon_size' data-animation-speed='$animation_speed_time' data-animation='$enable_animation' data-animation-delay='$animation_delay' data-color='".strtolower($color)."'>
<span>".get_template_directory_uri()."/css/fonts/svg/$image</span></div>$ending";

Personally I prefer to format string using sprintf instead of pasting the string together using dots. You could put the $svg_icon string together using sprintf with only the <div> tag. After that just wrap an <a> tag around $svg_icon if $icon_link is defined:
$svg_icon_format = '<div class="svg-icon-holder" data-size="%d" data-animation-speed="%d" data-animation="%d" data-animation-delay="%d" data-color="%d"><span>%s</span></div>';
$values = array(..enter values here..);
$svg_icon = sprintf($svg_icon_format,$values);
if(isset($icon_link) && isset($icon_link_rel)) {
$svg_icon = sprintf('%s',$icon_link,$svg_icon,$icon_link_rel);
}
Disclaimer: This code is not tested. Please look at the sprintf documentation I linked and try writing the code yourself.

First, do not write everything on one line, so it fits on the screen here on SO (and maybe in your code too).
Second, I would use instring variables. In php you can use singlequotes, where your string gets used as-is, or you can use doublequotes, where you can use variables in it. like echo "Hey, my name is $name"; $name here would get exchanged by the value of the variable. If you need doublequotes in the string, you can escape them with a backslash like \"
Third, you can use inline if-else, folowing syntax: $str = boolean ? "str if true" : "str if false"
$svg_icon = isset($icon_link) ? "<a href=\"$icon_link\"
rel=\"$icon_link_rel\">" : '' . //add your opening <a> if needed
"<div class=\"svg-icon-holder\"
data-size=\"$icon_size\" data-animation-speed=\"$animation_speed_time\"
data-animation=\"$enable_animation\"
data-animation-delay=\"$animation_delay\"
data-color=\"strtolower($color) \"><span>"
. get_template_directory_uri()
. "/css/fonts/svg/ $image </span></div>"
. isset($icon_link) ? '<\a>' : ''; //add your closing <\a> if needed

Related

How to correctly write <img src> in php without escaping to HTML

I am having trouble with my PHP code. I've been changing everything for 6 hours and I still get Parse errors no matter what I do. This is the code:
$slider3 = '<img src="'templates/' . $this->template . '/images/slider/slider3.jpg'">' . '" alt="' . $sitename . '" />';
The only way I can figure to not get it to throw an error is by writing it this way:
$slider3 = '<img src="templates/" . $this->template . "/images/slider/slider3.jpg" . "/>"';
but I don't think that's right.
I want $slider3 = "templates/MYTEMPLATE/images/slider/slider3.jpg" then later I will echo $slider3;
I get so confused with all the single and double quotation marks. I think the first one is right - I look at it and study it and it looks right to me. But it throws a parse error.
$slider3 = '<img src="templates/'.$this->template.'/images/slider/slider3.jpg"/>';
should work.
Explanation:
'<img src="templates/'
is a single-quoted string, which happens to contain a double-quote (which is needed for the html src attribute, or any other html attribute value really)
.
(dot) is the string concatenation operator. It concatenates ("glues") the first string together with...
$this->template
which is presumably a string containing the name of the template (not clear from your code example). Note that if $this->template comes from user input, or an otherwise unvalidated source, it could be used for cross-site scripting, eg. if it contains "><script>alert("XSS!")<script>, javascript is executed in the browser!
.
another concatenation with...
'/images/slider/slider3.jpg"/>'
which is another single-quoted string which happens to contain a double-quote, ending the src attribute value.
Try this:
$slider3 = '<img src="templates/"' . $this->template . '"/images/slider/slider3.jpg"/>';
$template = "MYTEMPLATE";
$slider3 = '<img src="templates/'.$template.'/images/slider/slider3.jpg"/>';
echo $slider3;
Will echo - >
<img src="templates/MYTEMPLATE/images/slider/slider3.jpg"/>
Just write:
<?php
$templates = "var";
echo "<img src='templates/${templates}/images/slider/slider3.jpg'/>";
it will result in
<img src='templates/var/images/slider/slider3.jpg'/>

Defining <img src = according to the end of the link

How do I set the src= of a <img> element, according to the end of my link?
Example 1:
Link:
http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=325356456.png
<img> element in see-img.php file:
<img src="http://www.endertec.com.br/hf/do.php?imgf=325356456.png"/>
Example 2:
Link:
http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=342424234.png
<img> element in see-img.php file:
<img src="http://www.endertec.com.br/hf/do.php?imgf=342424234.png"/>
I.E.: I want to know if there is any script that I can use in see-img.php do what I was demonstrating above file.
Edited
Try this:
<?php
//$str = 'http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=342424234.png';
$str = 'http://www.endertec.com.br'.$_SERVER['REQUEST_URI'];
$src = str_replace('see-img.php?img=' , '' ,stristr($str , 'see-img.php?img='));
echo '<img src="'.$src.'"/>';
?>
In PHP you could do this:
$img_url = isset($_POST['img']) ? $_POST['img'] : null;
$img_file = isset($_POST['imgf']) ? $_POST['imgf'] : null;
Then with that $img_url you can do this:
if (!empty($img_url) && !empty($img_file)) {
echo '<img src="' . $img_url . '?imgf=' . $img_file . '"/>';
}
The idea is to get the URL values which are known as post values, assign them to a variable & then do a check where you echo the values into <img src= tags.
But that is the best that I can do based on the lack of detail in your question. But the concept is solid and should work in PHP.
You could try using a built in php function know as sttrpos, it will return an int with the position where the substring you need begins. Then a normal php substring will do the trick.

Insert function name with php

I'm trying to do a simple task, insert a second function name under "onmouseover" but probably something is wrong with the syntax.
echo '<div onmouseover="changeText(); <?php if($title==""){echo changeViz();}; ?> ">';
I probably need to escape some quotes and add some, but i can't figure out the correct solution.
Thanks
Nothing it's working. Let me give you the complete code...:
echo '<div class="frame" onmouseover="changeText(\''.$text[$i].'\'); <?php if($title[$i]==""){echo changeViz();}; ?>">';
You are nesting <?php ?> inside existing php code, which is a syntax error. Instead, concatenate in the javascript function changeViz() as a quoted string.
This version uses a ternary operator to duplicate the if() statement you had originally.
echo '<div onmouseover="changeText(); ' . ($title == '' ? 'changeViz();' : '') . '">';
The ternary operation here will concatenate changeViz(); onto the echo string if $title == "", or otherwise just concatenate on an empty string.
Update after seeing full code:
You have the quote escaping correct in the first part.
echo '<div class="frame" onmouseover="changeText(\'' . $text[$i] . '\'); ' . ($title == '' ? 'changeViz();' : '') . '">';
You can make your code much more readable if you do not try to do everything in one line:
$onmouseover_action = "changeText(); ";
if($title==""){
$onmouseover_action .= "changeViz(); ";
}
echo '<div onmouseover="'.$onmouseover_action.'">';
It makes your code easier to maintain, and you have less need to comment it, because it describes itself quite much better.
Try this:
echo '<div class="frame" onmouseover="changeText(\''.$text[$i].'\'); '. ($title[$i]=="")?'changeViz();':'').'">';

Adding A Dynamic Link In Php

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

render php variable comming from database

what I want to do is want to save php variable in database (suppose {$baseUrl} ) and I am getting the data on php page with echo command and on the same page I have defined $baseUrl='/public'. I want to get the value for the base url but I'm getting simply {$baseUrl} not '/public'
in db I have <img src="{$baseUrl}/img.jpg" />
on page I have
$baseUrl = "/public";
echo $content
it is giving <img src="{$baseUrl}/img.jpg /">
how can I get <img src="/public/img.jpg" />
Of course. Strings are strings, not PHP code. You'll have to replace it yourself, e.g.:
<?php
$baseUrl = '/public';
$string = '<img src="{$baseUrl}/img.jpg" />';
$replacements = array(
'{$baseUrl}' => $baseUrl,
);
echo strtr($string, $replacements);
I think what you want to do is a string replace. The variable pointer ($baseUrl) is a string that comes from the database. If you echo it, it is still just a string. What you need to do is something like this:
<?php
echo str_replace('$baseUrl', $baseUrl, $varFromDB);
?>
Or do I understand your question wrong?
With
str_replace($content, '{$baseUrl}', $baseUrl)
.
I am guessing that you are using the wrong quotes:
echo '<img src="{$baseURL}/img.jpg" />';
rather than
echo "<img src='{$baseURL}/img.jpg'/>";
You want the $baseUrl variable to be evaluated? You have to put the variable outside of the string definition:
echo '<img src="' . $baseUrl . '/img.jpg" />';
or put it between double quotes (strings enclosed in double quotes are parsed by PHP):
echo "<img src=\"{$baseUrl}/img.jpg\" />";
Based on your comments, you need this solution:
$content = str_replace("{$baseUrl}", $baseUrl, $content);
You may want to use the eval() function...
This is not a good idea, but it would achieve what you want.

Categories