PHP script tags - php

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>

Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)

Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.

Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}

Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }

That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

Related

php how to reload "require" include file after submit in self submitting form

I am making a self processing php form. I have a header.inc and footer.inc both called with a require statement. My problem lies in my header uses a $title variable which I would like to update after post. Currently my variable is changing and I can echo it in my response (thank you) page, but the header does not reload to reflect the change.
I understand I could call the title in my main PHP file, but I was hoping to find a way to reload the require(header.inc) file and continue processing the form.
<?php
$title = "XX";
$title2 = "Form";
$thisScript = htmlspecialchars($_SERVER['PHP_SELF']);
require("htmlHead.inc");
function changeTitle()
{
$GLOBALS['title2'] = "Results";
}
changeTitle();
if (!isset($_POST['submit']))
{
echo <<<FORMDOC1
<form action="$thisScript" method="post" action=" "
onSubmit="window.location.reload()">
FORMDOC1;
else
{
//random code
}
require("htmlFoot.inc");
?>
header.inc file in question:
<?php
echo "<!doctype html> <!-- Author: $author -->\n";
echo "<html lang=\"en\"><!-- Date Written: $dateWritten -->\n";
echo "<head> <!-- Description: $description -->\n";
echo "\t<title>$title</title>\n";
echo "\t<title>$title2</title>\n";
echo "\t<meta charset=\"utf-8\" />\n";
echo "\t<link rel=\"stylesheet\" href=\"css.css\" />\n";
echo "</head>\n";
echo "<body>\n";
echo "<div id=\"wrapper\">\n";
echo "<h1>$title</h1>\n";
echo "<h2>$title2</h2>\n";
?>
You are setting the title after including the header. Therefore, the value hasn't changed yet at the time php has output the header content.
Try following this general structure
if(isset($_POST['submit')) {
//process the form
include('header.inc');
//display confirmation
}
else {
include('header.inc');
//display the form
}
include('footer.inc');

PHP if/else without echo

How do I replace echo with proper html codes? Since there will be hundreds of html codes, using echo doesn't make sense.
<?php
if ($this->item->catid == 9) {
echo "yes, it exists";
}
else {
echo "no, it don't exist";
}
?>
I'm new to PHP.
Do you mean, how can one cleanly output many lines of HTML conditionally without having to echo each individual line?
If that's the case, something like this would do the trick:
<?php
if ($this->item->catid == 9) {
?>
<!--- put all the raw output you like here --->
<?php
} else {
?>
<!--- put all the raw output you like here --->
<?php
}
?>
The "raw output" would be anything sent to the browser. HTML, JavaScript, etc. Even though it's outside of the server-side PHP tags, as far as the PHP processor is concerned it's still between the { ... } brackets. So it's only output as part of that conditional block.
There is two way to do it :
1) As suggested by David, by closing your php tags to write raw HTML.
<?php
if ($this->item->catid == 9) {
?>
// HTML goes here
<?php
}else{
?>
// HTML goes here
<?php
}
?>
But if you're planning to write a lot of text it might be a be hard to read your code in the end so you can use the following.
<?php
$htmlOutput = '';
if ($this->item->catid == 9) {
$htmlOutput .= "yes, it exists";
} else {
$htmlOutput .= "no, it doesn't exist";
}
?>
You create a variable that will contain all your HTML by appending a part of it everytime you need to so in the end you'll only need to print a single variable.

Rendering a Global or a Var in a Php echo

I found a good script anti spam robots. To implement it in my dynamic pages I have to paste this code:
<?php echo hide_email('test#test.com'); ?>
Since my pages are dynamic, my emails are stored in Globals
%%GLOBAL_Email%%
<?php echo hide_email('%%GLOBAL_Email%%'); ?> <--- The email is not rendered
Even if I transform the Global in a var it does not work, I tryed the following:
<?php echo hide_email(' . $email . '); ?>
<?php echo hide_email('" . $email . "'); ?>
Answer:
<?php echo hide_email($email); ?>
The question was simple, the answer too.
Here is the answer:
<?php echo hide_email($email); ?>

php if echo something else echo else for html

So here's my code, I try to make for my pagination function to echo something if is on homepage and echo else if is on another page like page=2 or page3 ++
<?php if(empty($_GET) or ($_GET['pg']==1)) { echo ' ?> Html codes content and php <?php '; } else { echo '?> Else html codes content and php <?php '; } ?>
But is not working, i'm sure is from the " ' " or " '' " something i put wrong but where? where or what is the problem
Don't put ?> in the echo statement.
<?php
if(empty($_GET) || $_GET['pg'] ==1) {
echo 'HTML codes content';
} else {
echo 'Else html codes content';
}
?>
You can also do it by closing the PHP and not using echo:
<?php
if (empty($_GET) || $_GET['pg'] ==1) { ?>
HTML codes content
<?php else { ?>
Else html codes content
<?php } ?>
You can use a ternary operator to make it simpler. Also it's better to use isset() because even if $_GET is not empty, that doesn't mean that $_GET['pg'] exists, so it will generate warnings.
Anyway as pointed out above, the problem is that you are using ?> inside the echo statement, which is incorrect.
You can do for example:
<?php if ((isset($_GET['pg'])) && ($_GET['pg']==1)) { ?>Html codes content and php<?php } else { ?>Else html codes content and php<?php } ?>
Using a ternary operator:
<?php echo ((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>
Using a ternary operator and short tags:
<?=((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>
You cannot have PHP code in echo, because PHP will interpret your code in a single pass.
Your code should be like this :
<?php
echo (empty($_GET) || ($_GET['pg']==1)) ?
'Html code':
'Another HTML code';
?>
If you need to output some PHP code, there is always a better way to accomplish it, you can include some file that contains the php code you want to add.
You can use this way.
<?php if(empty($_GET) || $_GET['pg'] ==1): ?>
<p>HTML codes content</p>
<?php else: ?>
<p>Else html codes content<p>
<?php endif; ?>
Note that : I used direct html code.

PHP $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Categories