Open In App

How to embed PHP code in an HTML page ?

Last Updated : 12 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page. 

We can use PHP in HTML code by simply adding a PHP tag without doing any extra work. 

Example 1: First open the file in any editor and then write HTML code according to requirement. If we have to add PHP code then we can add by simply adding <?php ….. ?> tags in between and add your PHP code accordingly.

PHP




<!DOCTYPE html>
<html>
  <head>
    <title>PHP</title>
  </head>
  <body>
     <h1>
        <?php
              echo "hii GeeksforGeeks "
          ?>
      </h1>
  </body>
</html>


Output:

Example 2: In this, we can use PHP code in different lines so that we can make a webpage according to the need and put code wherever necessary as shown in the below example

PHP




<html>
  
<body>
    <h2>Welcome to GeeksforGeeks</h2>
    <?php
        echo "Good morning";
    ?>
  
    <p>Good to see you</p>
        
    <?php
      $str = "This is GeeksforGeeks portal";
      echo " $str.";
    ?>
</body>
</html>


Output:

Example 3: In this, we use PHP code in HTML document using the post method where we can pass value in HTML form and receive in the PHP post method. 

PHP




<html>
  
<body>
  
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
        Name: <input type="text" name="fname">
        <input type="submit">
    </form>
  
    <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST")
        {
            $str = $_POST['fname'];
              
            if (empty($str)) 
            {
              echo "String is empty";
            
            else 
            {
    ?>
               <h1>
                 <?php echo $str ?>
               </h1>
    <?php
            }
        }
    ?>
</body>
</html>


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads