close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com




PHP - Include and Require

PHP allows us to create various elements and functions, which are used several times in many pages.

File inclusion that helps to include files in various programs and saves the effort of writing code multiple times.

PHP allows you to include file so that a page content can be reused many times.

It is very helpful to include files when you want to apply the same HTML or PHP code to multiple pages of a website with the include or require statement.

  • include() function
  • require() function

  • PHP - include()

    This function is used to copy all the contents of a file called within the function.

    This happens before the server executes the code.

    Syntax : include()

    
    include 'filename ';  
    Or   
    include ('filename');  
    

    Let's see a simple PHP include example.

    Example : include()

    File Name : list.html

     
     
     <li>MySQL</li>
     <li>HTML</li>
     <li>CSS</li>
     <li>Java Script</li>
     
    

    Save File : include.php

    
    <?php
        echo "Programming List";
        include("list.html"); 
        
     ?>

    It will produce the following result −

    Result

    Run File : localhost/include.php

    Programming List

  • PHP
  • MySQL
  • HTML
  • CSS
  • Java Script



  • PHP - require()

    PHP require is similar to include, which is also used to include files.

    The only difference is that it stops the execution of script if the file is not found whereas include doesn't.

    Syntax : require()

    \
    
    require 'filename';  
    Or   
    require ('filename');    
    

    Let's see a simple PHP include example.

    Example : include()

    Save File : list.html

     
     
     <li>MySQL</li>
     <li>HTML</li>
     <li>CSS</li>
     <li>Java Script</li>
     

    Save File : require.php

    
     <?php
        echo "Programming List";
        require("list.html"); 
     ?>

    It will produce the following result −

    Result

    Run File : localhost/include.php

    Programming List

  • PHP
  • MySQL
  • HTML
  • CSS
  • Java Script

  • PHP include vs PHP require

    Both include and require are same. But if the file is missing or inclusion fails, include allows the script to continue but require halts the script producing a fatal E_COMPILE_ERROR level error.

    Advantage of Include and Require

  • Code reusability
  • Easy editable