Conditional embed HTML between PHP code blocks? - php

I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?
<?php if (something) { ?>
<p>Hello</p>
<?php } ?>
The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.
The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).
<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>
I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.
P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.

Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/
Here is what your doing:
<?php
//Anything inside me php processes
if($something)
{
echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>
Quick Note: It is good practice to separate your PHP from your HTML
<?php if ($something) { ?> <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.

In your first example it is indeed true that <p>Hello</p> will be rendered if and only if 'something' returns true.
If you close a php tag with ?> but have an 'unclosed' execution, like if (blah) { ..., the PHP engine understands your desires and does accordingly.
Why?
The PHP engine is kept 'waiting' until the execution is closed with } and then the final result is evaluated and the browser continues on with the lines below.
Obviously if you leave out the final } you will see some errors, which tells you that PHP was expecting you to finish what you started and you did not

Both the php and html are parsed in-line. So, as it moves down your script it will run php scripts within tags, and display html in the order which they are placed. For example:
<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo
This will show as:
<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>
Basically just think of it as the server reading down your script and parsing whatever it sees as it goes. If there is html, it will display it and if there is php which does some sort of calculation and then spits out html, it will show the spat out html.

You can write php code anywhere in HTML using php code block
<?php echo "whatever " ?>
or
<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>
and if you use control structure ( if, switch etc.. ) then it will behave like all other languages, means if something is true then it will execute the part written between { }.
so if you write an undefined variable in if condition then it will not execute code block of because undefined variable is treated as false condition .
additionaly you can check any variable value by var_dump($variable)

PHP's Alternative syntax for control structures
<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
<p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
<p>The other thing is true! meh</p>
<?php else : ?>
<p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...

Related

Insert data in HTML from php

I trying to put user data from PHP in HTML form, like name, email, address, etc. But i don't know what i have to do to work it.
Already tried:
<?php
session_start();
$test='some name';
$_SESSION['name']='some name';
?>
<!-- AND -->
and nothing happened.
SOLVED CODE:
<?php
session_start();
$test='some name';
?>
<a><?= $test ?></a>
The PHP manual has a page introducing the PHP tags:
When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them.
Note that "interpreting the code" is not the same as displaying the result of that code. For instance, you could write <?php $test = 'hello'; ?> to assign a new value to a variable, and it won't cause anything to be output.
To output a string, you can use the echo and print keywords. Note that these are not functions, so do not have parentheses around their arguments; as noted in the manual, including redundant parentheses will sometimes work, but can be misleading. So the following output the variable $test into the page:
<?php echo $test; ?>
<?php print $test; ?>
As the PHP tags page I linked to earlier says:
PHP includes a short echo tag <?= which is a short-hand to the more verbose <?php echo.
So you can also use:
<?= $test ?>
However, you also have a second problem, which is nothing to do with PHP, and will happen if you hard-code a URL into your HTML like this:
Nothing will appear in the browser! Why? Because you've defined the destination of a link, but haven't defined any text or content to click on; you need it to look like this:
Click me if you dare!
So put that together, you might write this in PHP:
<?= $linkDescription ?>
Change this
to this
or to this if you want to see the data on the html page
<?php $test; ?>
<?php echo($test); ?>
Do note that there are better ways to display such data. Check this out:
https://www.w3schools.com/php/php_echo_print.asp

PHP Literal output with ?> in function definition

When writing PHP code in the past, I have often been plagued by the awkwardness of having to nest my HTML code in calls to print, echo or similar. This is alleviated to some degree by the ability to make parts of the code be literally outputted by closing the PHP tag and reopening it again after the output, eg:
<?php /*DoSomeStuff*/ ?>
Some HTML code.
<?php /*SomeMorePHP*/ ?>
However, I have never been clear on how this interracts with functions. For example, it is unclear to me if writing:
<?php
function myFunction() {
?>
Some HTML
<?php
}
?>
Will produce a function which upon being called will output that HTML, if the function will be parsed as empty but output that HTML during parsing, or neither, both or if this construct is just illegal entirely?
I am reluctant to base all my results on just trying this on some particular instance of PHP as I do not wish to beleive it works while in reality it might be undefined behaviour or think it doesnt work while I might just have an old or buggy PHP and I have never seen this construct used in any code.
Ideally I am looking for some kind of reference to documentation or specification which would clear this up.
I know this is not exactly answering your questions with a lot of references, but: This is valid (PHP Docs), although it doesn't look very nice, it's a common practice in some old but BIG frameworks.
You can try this and see what happens:
function htmlOut() {
?>
Some HTML output
<?php
}
htmlOut();
By the way I found an example, the default skin of MediaWiki (I would say they know what they are doing) is using just the method you have described.
/**
* Outputs the entire contents of the (X)HTML page
*/
public function execute() {
/**
* some code
*/
// Output HTML Page
$this->html( 'headelement' );
?>
<div id="mw-page-base" class="noprint"></div>
<div id="mw-head-base" class="noprint"></div>
<div id="content" class="mw-body" role="main">
<a id="top"></a>
<?php
/**
* some more code
*/
}
See the full code here: MediaWiki GitHub
Basically it will work as you expect it to be, which means that this HTML will be printed only on function invoke.
There's probably no documentation for your use case, but it's similar to condition expressions.
You could ask if similar question for code below:
<?php if ($expression == true): ?>
HTML1
<?php else: ?>
HTML2
<?php endif; ?>
Will PHP print both HTML parts, or only one depending on the condition?
Well, the doc says clearly that it works as it is expected to be.
I think we can say it's the same for functions/methods, because it's just "a block of code". It works with the same rule in many other cases like loops or swich
Reference: http://php.net/manual/en/language.basic-syntax.phpmode.php Example #1

how does php work when we are out side php in html mode?

i am a bit confused when i use conditional statements like
<?php
if(isset($_POST['somevalue'])){
?>
<h1> this is out side php mode now </h1>
<?php
}else {
?>
<h1> again its out php mode </h1>
<?php
}
?>
but yet it still works i mean if $_POST['somevalue'] is set then it outputs "this is out side php mode now" if not it outputs "again its out php mode" my question is if i am outside php mode how does it work then?
I think your question is "how PHP works".as we know php is a server side language.it executes in the server but the scope of the html code will be inside the if loop.so
<?php
if(isset($_POST['somevalue'])){
?>
will be evaluated in server and not in the html part and that will be either true or false.
so after the execution in server your code in front end i.e. in the html part will be like this
<?php
if(1){
?>
<h1> this is out side php mode now </h1>
//as above code is markup language so it will be interpreted by the browser
<?php
}else {
?>
<h1> again its out php mode </h1>
<?php
}
?>
NOTE: the delimiters is for the server to know that the code inside the tag is php code and it will execute it accordingly.
Although you have closed off the executable section of the PHP code, the surrounding if statement and the curly braces will actually have a higher priority as to what is executed and what isn't.
<?php
if
{
// This is considered inside the statement
// and will only be sent if the execution
// makes it inside the statement.
?>
...
<?php
}
else
{
}
?>
// Anything here is simply sent to the browser
// as it will always executed.
<?php
// more code etc
?>
Anything inside the IF statement is considered part of the IF - even if it contains close/open PHP tags.
Basically the PHP control structure overrides open/close tags. This means any sort of if, switch, function etc etc has a higher priority than open close tags.
That's one thing I love about php.
Initially, the main reason is as #Fluffeh mentioned that you are still within the "if" statement.
One way I could put it is that, PHP allows to be embeded in side HTML code. As long as the file has a .php extention then (someone correct me if I'm wrong) Apache knows to use the PHP processor to process that file. It will process the php coding and display the HTML sections in it as well.
Your question is some what similar to
<?php
$name = "Tom";
?>
<h1>Hello <?php echo $name;?>!</h1>
The result will come out as Hello Tom!
it is the same idea as it is inside the php.. satisfy each of the condition and it will run its corresponding statement..
this is one of the best features of php, which allow us to use native html codes rather than putting it inside echo.
A PHP file is processed as plain text/html until it reaches a <?php tag when it executes the php code. When it reaches the closing ?> it processes it as plain text again.
This is exactly the same, but with echo and quote marks around the html you want to print. If you're having trouble reading the code I suggest indenting as needed.
<?php
if(isset($_POST['somevalue'])){
echo "<h1> this is out side php mode now </h1>";
}else {
echo "<h1> again its out php mode </h1>";
}
?>
The way you posted it.
<?php
if(isset($_POST['somevalue'])){
?><h1> this is out side php mode now </h1><?php
}else{
?><h1> again its out php mode </h1><?php
}
?>

Is there anyway to produce readable HTML source from PHP?

I'm not very experienced at php, so if there's an easy function for this, I'll feel like an idiot.
When coding in PHP, at the point where you need to echo some HTML code, I have found I have either one of two options.
A: echo "<!--html text here-->";
B: echo "\t\t\t<!--html text here-->\n";
If I were to use method A throughout the code, looking at the php code from client side using view-source produces a solid block of code which is difficult to read.
If I were to use method B, it looks fine client-side, but the actual source code looks messy.
Is there anyway to keep both server and client-side appearance clean?
Something like this
<?php
//php code here
?>
//html code
<h3> <?= $justADynamicVariable ?> </h3>
<?php
//continue php code
?>
Un-readable front end code is caused by poor factoring of your PHP code
The wall-of-text issue occurs because your code is messy. You have logic and display code in the same place (evident from the fact that you're echoing HTML from a PHP block) and this will always produce unreadable and ugly code.
Look at Model-View-Controller pattern, and separate out your logic code from your display code. Then, write your display code in a primarily HTML format with some in-line PHP:
<div>
Welcome back <?= $this->username; ?>
</div>
If you're having to echo HTML code from a PHP block, your code is probably factored wrong.
Other useful tricks to produce readable code:
Use alternative PHP control blocks
This:
<div id='somediv'>
<?php if($something): ?>
Some stuff
<?php endif; ?>
</div>
is infinitely more readable than this:
<div id='somediv'>
<?php if($something) { ?>
Some stuff
<?php } ?>
</div>
And it's definitely better than this which is probably what you're using now:
<?php
echo "<div id='somediv'>";
if($something) {
echo "Some stuff";
}
echo "</div>";
?>
You can just close the php tag (?>), write the html block and return to php (
Use a templating engine, like Twig http://twig.sensiolabs.org/ it allows you to separate your logic out of your templates so you can write really easy to markup with simple syntax to drop in dynamic variables.
or
Use a browser like Chrome, which will auto indent your source for you when you use the Web Developer Tools http://discover-devtools.codeschool.com/. You can even copy paste the results really quickly to a new file. In general, it's a bad idea to fret over outputting well spaced html since software can clean it up so easily.
There are lot's of ways to produce html, depending or it's a single line or an entire block of HTML.
The important thing is readability.
echo "<div><p>Hi ".$name."</p></div>";
Isn't unreadable persé, it might be annoying because it won't get highlighted in many IDE's.
This is a good reason to always seperate html and php, meaning always put html parts outside of your php tags.
So you could end your php block before and open it again after :
if(TRUE) {
?>
<div><p>Hi <?php echo $name;?></p></div>
<?php
}
If you have PHP within a large file mostly containing html you are better of using php control blocks:
<!--html text here-->
<?php if(TRUE):?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
</php endif;?>
<!--html text here-->
You could also use heredoc
echo <<<EOD
<div>
<p>This is html</p>
</div>
EOD;
Or output buffering:
ob_start();
?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
<?php
$html = ob_get_clean();
echo $html;

Cakephp Local session logic

I have a simple if checking for a customer_id in the session.
<?php if($this->Session->read('customer_id')){ ?>
<?php echo $this->element('watchlist'); ?>
<? } else { ?>
<?php echo $this->element('recently_sold'); ?>
<?php } ?>
It's very simple, but when I visit the page, the customer_id is null, and neither of the elements show up. When I login, BOTH the elements are displayed. Something is really strange with the logic here and I'm not sure where to start. I tried checked for null and using is_numeric, but still the same results. Has anyone had any issues with sessions on their local environment like this?
Thanks
Does your PHP set-up recognise the PHP short tags <? ... ?> as opposed to <?php ... ?> ?
If it doesn't then your } else { statement will not be recognized as PHP and so both echo's will happen when the if-statement is true (and you should see the "<? } else { ?>" printed out as text in your source code if you look carefully).
Like #Chris Hendy says above it's confusing to keep opening and closing PHP tags for no reason.
Short tags should not be used as they are a server setting and most servers do not have them on by default. From PHP 5.4 short tags are on a switch with the difference that the "echo short tag "

Categories