.php or .html
A file may consist entirely of PHP, or a mixture of HTML and PHP. In either case, all PHP scripts are encloded in a tag:
<!DOCTYPE html> <html> <body> <?php echo "<h1>This is PHP</h1>"; ?> </body> </html>
<?php // the \n line breaks are used to made the generated HTML code readable echo "<!DOCTYPE html>\n"; echo "<html>\n"; echo "<body>\n"; echo " <h1>This is PHP</h1>\n"; echo "</body>\n"; echo "</html>\n"; ?>
If the file is saved with a .php extension, then any php blocks will the executed by the server. Non-php blocks will be treated as html.
If the file is saved with a .html extension, then it will not be parsed by the PHP compiler unless the server is configured to do so. In this case, all PHP blocks will be ignored.
- If your page is static (only has HTML code) – use .html
- If your page contains any PHP code – use .php
Building web pages generated by PHP code
You can generate the HTML returned to a browser by a .php file in the following ways:
- If the PHP script is contained within the same page as a submitted form, then the entire page will be reloaded when the GET or POST script is executed. Any output produced by the script will be included according to the position of the script within the HTML. This is the simplest solution if you wish to stay on the same web page when a form is submitted.
- If you want to generate a completely different page, then the form should load a different .php file. In this case, the PHP file will have to contain all the HTML elements required to build the new page.
include
You should already be familiar with using external style sheets to share styles across many pages on a site.
Any repeated segments of HTML or PHP can be saved in separate files and then used in pages as necessary. The content of the included file is treated as if it were in the file itself.
<?php echo "<p>Server date/time = " . date("m/d/y") . " " . time() . "</p>"; ?>
<nav> <ul> <li><a href="home.html">Home</a></li> <li><a href="sport.html">Sport</a></li> <li><a href="music.html">Music</a></li> <li><a href="study.html">Study</a></li> <li><a href="drama.html">Drama</a></li> </ul> </nav>
<!DOCTYPE html> <html> <body> <header>...</header> <?php include "snippets/serverDateTime.php.html"; ?> ... <?php include "snippets/navBar.html"; ?> ... </body> </html>