Sunday, December 29, 2024
Google search engine
HomeLanguagesHow to insert PHP code in HTML document using include or require...

How to insert PHP code in HTML document using include or require keyword ?

PHP is an HTML embedded server-side scripting language.  The syntaxes are most similar to ‘C’  and ‘JAVA’ languages. The user or developers have a facility where they can insert the PHP code into an HTML document without having any problem.

We can insert any PHP file into the HTML code by using two keywords that are ‘Include’ and ‘Require’.

PHP include() function: This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called. This happens before the server executes the code.

Syntax:

include 'php filename';

Example 1: Consider a PHP file name ‘natural.php’ which contains the following code.

natural.php




<?php
  $i = 1;
  echo "the first 10 natural numbers are:";
  for($i = 1; $i <= 10; $i++) { 
    echo $i;
  }
?>


Output:

 

Example: Insert the above code into an HTML document by using the include keyword, as shown below.

PHP




<!DOCTYPE html>
<html>
<head>
    <title>inserting PHP code into html</title>
</head>
<body>
   <h2>Natural numbers</h2>
   <?php include 'natural.php'?>
</body>
</html>


PHP require() function: The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called.

Syntax:

 require 'php filename' 

Example 2: We can insert the PHP code into HTML Document by directly writing in the body tag of the HTML document.

PHP




<!DOCTYPE html>
<html>
<head>
    <title>inserting php code into html </title>
</head>
<body>
   <h2>natural numbers</h2>
<?php
  $i = 1;
  echo"the first 10 natural numbers are:";
  for($i = 1; $i <= 10; $i++) {
    echo $i;
  }
?>
</body>
</html>


Output:

natural numbers
the first 10 natural numbers are:12345678910

Example: To insert the above code into an HTML document by using the ‘require’ keyword as shown below.

PHP




<!DOCTYPE html>
<html>
<head>
   <title>inserting PHP code into html</title>
</head>
<body>
   <h2>Natural numbers</h2>
   <?php require 'natural.php'?>
</body>
</html>


Output:

Natural numbers
the first 10 natural numbers are:12345678910

Difference between the include() function & require() function:

In the case of the include() function, if we insert a file by using the include keyword it produces a warning and continues the execution even if any error is found, whereas, in the case of require() function, if we insert a PHP file by using the require keyword, it will stop the execution if there is an error occurred.

RELATED ARTICLES

Most Popular

Recent Comments