Inserting PHP Code Into a Web Page

June 3, 2009 by: Allen Sanford

Most beginners in PHP are under the assumption that only PHP code can be placed in .php files. This is an incorrect assumption. Today I am going to show how to insert PHP code into HTML markup and place all of it in a .php file.

Inserting PHP code into HTML markup allows us to create interactive, dynamic, pages for our website. In order to achieve this we simply place any HTML markup that is static out side the and ?> , the opening and closing delimiters for PHP code. Also note that we can place multiple PHP code sections in our HTML markup by using different instances of the PHP delimiters.

When the web server receives a request from the web to display our .php file the PHP interpreter will parse all of the code between the delimiters   as PHP code. The PHP interpreter will then return the output of this PHP code to the web server to be inserted into the web page just before it is passed to the requesting browser. The users who are viewing this web page will not be able to see the PHP code, they will only be able to see the resulting output from the PHP code that has been executed on the server.


?Download example.php
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                                   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>PHP Example</title>
    </head>
    <body>
<h1>Example PHP</h1>
 
        <?php echo "Hello World"; ?>
    </body>
</html>


When you get ready to save the PHP files you have created you have to save them with a .php extension, however some text editors do not recognize the .php extension, so you may have to enclose the filename in quotation marks like so, “example.php”. It may be possible that your PHP configuration is configured to parse other file extensions as PHP such as .phtml, .html or .htm, but in any case if your server is configured to parse a certain extension then you are allowed to place PHP code into files with those extensions configured.

Filed under: PHP
Tags: , , , ,

Comments

3 Responses to “Inserting PHP Code Into a Web Page”
  1. I observe that your writing is rather insightful as it talks about plenty of insightful information. In Any Case, was thinking whether you would willing to exchange web links with my website, as I am searching to establish links to further spearhead and increase web exposure for my web site. I don’t really mind you setting my links at the home page, just accepting this web links on this particular page is good and enough. On the other hand, would you please message me back at my web portal if you are interested in the link exchange, I would really appreciate that. Thanks and hopefully to get a reply from you as soon as possible!

Leave a Reply