Cover Image for How to use PHP in Html
87 views

How to use PHP in Html

To use PHP in HTML, you need to save your HTML file with a .php file extension. This tells the server to process the file as PHP code. Here’s an example of how you can use PHP within an HTML file:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>PHP in HTML Example</title>
  </head>
  <body>
    <h1>Welcome to my website</h1>
    <?php
      // PHP code goes here
      $name = "John";
      $age = 25;
      echo "Hello, my name is $name and I am $age years old.";
    ?>
    <p>This is a paragraph in HTML.</p>
    <?php
      // More PHP code
      $currentDate = date("Y-m-d");
      echo "Today's date is $currentDate.";
    ?>
  </body>
</html>

In the above example, the PHP code is enclosed within <?php ?> tags. You can write any PHP code inside these tags, and it will be executed on the server-side before the HTML is sent to the client’s browser. The PHP code can perform calculations, retrieve data from a database, generate dynamic content, and more.

In the example, we assigned values to variables $name and $age and then used them to display a message using echo. We also used the date() function to get the current date and displayed it using echo.

When you open this file in a browser with PHP support, the PHP code will be executed, and the resulting HTML will be displayed, including any dynamic content generated by the PHP code.

Note that to run PHP code, you need a server with PHP installed. You cannot run PHP code directly from a local HTML file without a server environment.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS