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';
}
?>
Related
I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>
I have created a custom wordpress post type everything works but my client asked me to insert a function that doenst show the button if the link field is empty that is also working but when I want to display the tekst or link the part where the php is inserted just doesnt shows up what am I doing wrong
I am able to get the data on other parts of this php file but not in this part of the page
<?php
$linktitle = $day_aray=get_field("under_shoe_button_title");
$linkexist = get_field("under_shoe_button_link");
echo($linktitle);
if (empty($linkexist)) {
echo '<html> <p></p></html>' ;
}
else {
echo '<html>
<a href="google.nl" class="button primary is-bevel box-shadow-3 box-shadow-4-hover expand" style="border-radius:5px;"
</html> <?php echo($linktitle); ?> <html><span></span>
<i class="icon-shopping-cart"></i></a>
</html>';
}
?>
If you would look carefully, you would notice, that you are echoing a string where, inside the string, you are trying to echo again. Even with little programming knowledge, you should understand, that it is not logical to do that.
The same goes for php opening <?php tag. You opened the tag at start of the page and later on, inside a string, you are trying to open it again. This does not work.
Instead, close the string (or escape it) and then add the echo option.
echo '<html>
<a href="google.nl" class="button primary is-bevel box-shadow-3 box-shadow-4-hover expand" style="border-radius:5px;"
</html>';
echo($linktitle);
echo '<html><span></span>
<i class="icon-shopping-cart"></i></a>
</html>';
And please, read the comments to you question and learn basic HTML
There are so many things wrong in your code
Firstly you are using echo inside echo you should use concatenation instead.
so you want to echo it like this
echo '<your html code>'.$linktitle.'<your other html code>';
Also your html code is wrong coz u are using many html tags.
My WordPress options panel has a section where the user can paste their logo's URL to show up in the header. If the input is blank, I want the Blog's title to show up instead on my header. The ID of the input is "nl_logo", so I added an if statement in my header.
<?php if ("nl_logo") { ?>
<img src="<?php echo get_option('nl_logo'); ?>">
<?php } else { ?>
<h1><?php bloginfo('name'); ?></h1>
<?php } ?>
The first part of the if statement works. However, anything below else doesn't work when I have no URL saved in my input. So, if the input is empty, how do I display something else with PHP? Or is there a different and better way to do this? For example, creating a function and calling the results to display with a simple line of PHP?
Try this... also try to understand it.
Keeping with the established coding style:
<?php $nlLogo = get_option('nl_logo'); ?>
<?php if (empty($nlLogo)) { ?>
<h1><?php echo(bloginfo('name')); ?></h1>
<?php } else { ?>
<img src="<?php echo($nlLogo); ?>">
<?php } ?>
That should atleast be valid PHP now. I don't know if the functions you are using are correct, but if they are this should work.
Here is a cleaner way to do it...
<?php
$nlLogo = get_option('nl_logo');
if (empty($nlLogo)) {
echo('<h1>'.bloginfo('name').'</h1>');
} else {
echo('<img src="'.$nlLogo.'">');
}
?>
Option three because I'm feeling "teachy" using a ternary. Probably a little long for this to be the best choice, but it is another option.
<?php
$nlLogo = get_option('nl_logo');
echo(empty($nlLogo) ? '<h1>'.bloginfo('name').'</h1>' : '<img src="'.$nlLogo.'">');
?>
Note I switched the if / else because I'm using empty and it just feels cleaner to do it this way instead of using !empty()
<h1><?php bloginfo('name'); ?></h1>
Should be
<h1><?php echo bloginfo('name'); ?></h1>
You could try the empty method to test if a string is empty. In context:
if(!empty($nl_logo)) {
// stuff
} else {
// other stuff
}
This does not make sense:
if ("nl_logo")
You're basically saying if the string exists then proceed, which it does, of course.
It makes more sense to take the input string:
$input = $_POST["postedInput"];
As an example, doesn't really matter as long as you know how you got the value into $input.
Now, you can use the ternary operator to determine whether you want to use the user's input or if you want to use the default title:
$img = $input == "" ? bloginfo($input) : get_option($input);
Depending on what your functions do.. if get_options returns a string then this will work.
Anyway, don't mis PHP and HTML, it will make things complicated and you'll be locked into bad design.
Note:
Make sure to check if the input is actually received, using isset.
You are testing for string "nl_logo" to be true. That returns always true.
try changing your code like this:
<?php
$nl_logo = get_option('nl_logo');
if (!empty($nl_logo)):
?>
<img src="<?php echo $nl_logo; ?>">
<?php else: ?>
<h1><?php bloginfo('name'); ?></h1>
<?php endif; ?>
Don't close the php tags.
Whatever html you need to write, just write it as echo statements within one big php block.
This should fix your problem
I am setting the value of a php variable to some html. i.e.
$_img = 'hehehehehe';
The variable is then shown in html after a br tag. But it doesn't execute the html in it. Rather it displays it like hehehehehe. So, is there any problem in my code! How can i do this thing?
Here is the code that displays that IN HTML,
<?php if ($_item->getComment()): ?> <br/><?php echo $this->escapeHtml($_item->getComment(), array('b','br','strong','i','u')) ?> <?php endif; ?>
<?php
$string = 'Hehehe';
echo $string;
?>
This works fine! The html is 'executed' and the link is displayed.
From your comment....
Here is the code that displays that <?php if ($_item->getComment()):
?> <br/><?php echo $this->escapeHtml($_item->getComment(),
array('b','br','strong','i','u')) ?> <?php endif; ?>
As predicted by many people, it looks like you are encoding the value when you display it.
I don't know what the $this->escapeHtml function is doing exactly, but it would appear to be doing an HTML Encoding on the string.
The result being that any tag, for example <a> will be sent to the browser as <a> which the browser will display as <a>. The browser will not see it as a tag, and will therefore not treat it as one.
So the simple answer is: don't encode the HTML...
<?php echo $_item->getComment(); ?>
I suspect you are just echoing the variable.
You need use the 'htmlspecialchars' method such as below.
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
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>";