render php variable comming from database - php

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.

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'/>

Echo javascript with a php function inside?

Oh boy! I cant get this to work. Any ideas on what the heck I'm doing wrong? Here's the code.
I'm trying to echo the script but use a php function to get the directory of the js file!!
Any help would be appreicated!!
echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';
I've tried dif scenerios with escaping but cant get this to output correctly.
Since you're already in the PHP context, you can simply concatenate the strings, like so:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Using sprintf() looks more cleaner, though:
echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());
Instead of opening another script tag inside the string, concat the string and echo. The <?php within your string will not be evaluated.
echo '<script src="'. get_some_function() . '/js/main.js"></script>';
Simple string concatenation:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Don't forget to properly escape the output of your function!
try doing this:
echo '<script src="'.get_some_function().' /js/main.js"></script>';
or this:
$value = get_some_function();
echo '<script src="'.$value.' /js/main.js"></script>';
Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed.
Similar is true for returned data from a function stored in a varaible. If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . If you are using double quotes, then no need to use . .
Like in all above answers, they have used . to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) :
$src = get_some_function();
echo "<script src=$src/js/main.js></script>";
But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes.
Hope this will help...

Add PHP variable inside echo statement as href link address?

I'm trying to use a PHP variable to add a href value for a link in an echo statement.
Here's a simplified version of the code I want to use. I know that I can't just add the variable into the echo statement, but I can't seem to find an example anywhere that works.
$link_address = '#';
echo 'Link';
Try like
HTML in PHP :
echo "<a href='".$link_address."'>Link</a>";
Or even you can try like
echo "<a href='$link_address'>Link</a>";
Or you can use PHP in HTML like
PHP in HTML :
Link
you can either use
echo 'Link';
or
echo "Link';
if you use double quotes you can insert the variable into the string and it will be parsed.
Basically like this,
<?php
$link = ""; // Link goes here!
print "Link";
?>
as simple as that: echo 'Link';
You can use one and more echo statement inside href
Link
link : "/profile.php?usr=firstname&email=email"
This worked much better in my case.
HTML in PHP: Link
The safest way to generate links in PHP is to use the built-in function http_build_query(). This function is very easy to use and takes an array as an argument.
To create a dynamic link simply echo out the result of http_build_query() like so:
$data = [
'id' => $id,
'name' => $name
];
echo 'Link';
If you want to print in the tabular form with, then you can use this:
echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;

Echoing through PHP an HTML image path which is dynamic

I am trying to echo a dynamic image path in PHP. I have this code that works
<?php
//this code works
$image = '<img src="img/newlogo.jpg">';
echo($image);
?>
//gives me an image
And this code that doesn't
<?php
//this code doesn't
$lineofstring='newlogo.jpg';
$image = '<img src="img/$lineofstring">';
echo($image);
?>
$lineofsting is actually going to be an image path which is stored in a mysql database where one row is filled with, for example: pictureabc.jpg, second row is picturexyz.jpg etc.
I am trying to pass on the searched imagepath name onto $lineofstring, which is then echo'd but no picture comes out. Where am i going wrong?
To interpolate variables in PHP, you need to use double quote marks ", e.g.
$image = "<img src=\"img/$lineofstring\">";
In this case, you need to escape the inner ".
You can also concatenate strings with .:
$image = '<img src="img/' . $lineofstring . '">';
if it's easier.
Your $lineofstring variable is in a string using single quotes. Single quotes tell PHP to use the string literally so your variable is not being recognized as a variable. Change it to double quotes or use concatenation to accomplish your goals.
$image = "<img src=\"img/$lineofstring\">";
Or:
$image = '"<img src="img'.$lineofstring.'">';
$profilepicture="images/profiles/".$myid.".gif";
$noprofilepicture="images/profiles/no_avatar.gif";
echo "<IMG SRC='";
if (file_exists($profilepicture)) {
echo "".$profilepicture."";
} else {
echo "".$noprofilepicture."";
}
echo "'>";

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.

Categories