BCA / B.Tech 8 min read

Embedding PHP in Webpages

PHP is a server-side scripting language that can be embedded in HTML to create dynamic and interactive webpages.

How to Embed PHP in HTML

To add PHP to an HTML webpage, the <?php ... ?> tag is used. This code is executed on the server and only the HTML output is shown in the browser.

Example:

                    
<!DOCTYPE html>
<html>
<body>
    <h1>PHP and HTML</h1>
    <?php
        echo "This is the output of PHP.";
    ?>
</body>
</html>
                    
                

The output of this code is:

This is the output of PHP.

Mixture of HTML and PHP

Dynamic content can be generated by combining HTML and PHP.

Example:

To show today's date:

                    
<p>Today's date is: <?php echo date('d-m-Y'); ?></p>
                    
                

Output:

Today's date is:

PHP Short Tags

In PHP, instead of <?php echo ... ?>, the <?= ... ?> tag can be used.

Example:

                    
<p>Hello, <?= "World!"; ?></p>
                    
                

Output:

Hello, World!

Advantages of Embedding PHP

  • Dynamic Content Creation: Dynamic content can be easily created with HTML through PHP.
  • Database Interaction: PHP helps in retrieving and displaying data from a database.
  • Reusable Code: PHP code written once can be used in many places.
  • Custom User Experience: PHP helps in generating personalized webpages according to the user.

Important Points

  • Always write PHP code inside <?php ... ?>.
  • Save a PHP script with a `.php` file extension.
  • PHP code is executed on the server, the browser only shows the HTML output.
  • Use server software like XAMPP, WAMP.

Conclusion

The combination of PHP and HTML is useful for creating powerful webpages. This is a simple and useful way for dynamic and interactive websites.