PHP Include & Require files Tutorial | KoderHQ (2024)

Home/Tutorials/PHP/Include & Require

In this tutorial we learn how to break up our code into different files in PHP, and allow other files to access them by using include and require.

  • What is include and require?
  • How to include a file
  • How to include a custom function
  • How to require a file
  • How to include_once or require_once
  • Summary

What is include and require?

Applications can rapidly grow too large and out of control. Classes, namespaces and functions help us organize sections of our code into something more manageable.

Includes and requires help even further by separating sections of code into physical files.

Instead of having one giant file for the entire application, we can create smaller, more specific files that are included when and where we need them.

How to include a file

First, we will need a file to include:

  1. Open your IDE and navigate to your PHPProjects folder.
  2. In the Project Pane, right-click on the PHPProjects folder and select New File.
  3. Name the file main.phpand press Enter or Return on your keyboard.
  4. Create another file, and name it file2.php

In the file2.phpwe will write a simple echo statement that will print a message to the screen.

Example: file2.php

<?phpecho "This text is included from file2.php";?>

In the main.phpfile, we are going to include the contents of file2.phpWe do this with the include keyword, followed by the filename in between quotes.

Syntax:

 include 'filename.php';

Example: main.php

When we run the main.phpfile in the browser, we can see that the echo statement in the file2.phpis shown.

The interpreter took all the content from file2.php,copied it, and pasted it into main.phpwhere the include statement is located. The following example will show exactly when the code from the included file becomes available.

Example: file2.php

<?php$fruit = ["Apple", "Banana", "Pear"];?>

Example: main.php

<?php// $fruit does not exist, raise errorecho $fruit[0] . "<br>";// Include file ith $fruitinclude "file2.php";// $fruit exists now, no errorecho $fruit[0] . "<br>";?>

When we run main.php,we get the following output.

Output:

Notice: Undefined variable: fruit on line 4Apple

The first line is an error, because at that point in the parsing of the script, the $fruit array didn’t exist.

Only after we include the file, does the $fruit array become accessible and we can print it to the page without error.

How to include a custom function

It’s time for a small challenge. Try to include and use the isEvenOdd() function from the Functions tutorial lesson, or any custom function you have in mind. If you get stuck, take a look at the code below.

Example: custom_math.php

<?phpfunction isEvenOdd($num) { if ($num % 2 == 0) { echo $num . " is an even number.<br>"; } else { echo $num . " is an odd number.<br>"; }}?>

Example: main.php

<?php// Custom math functionsinclude "custom_math.php";echo isEvenOdd(5);echo isEvenOdd(10);?>

How to require a file

When we requirea file, it’s the same as including it.

When including a file that doesn’t exist, the interpreter will raise an error, but the rest of the script will still execute.

When we require a file that doesn’t exist, the interpreter will raise a fatal error, and the script will stop execution.

Syntax:

 require 'filename.php';

Example: file2.php

<?php$fruit = ["Apple", "Banana", "Pear"];?>

Example: main.php

<?phprequire "file2.php";foreach ($fruit as $item) { echo $item . "<br>";}echo "I print if an include fails, but not if a require fails."?>

When we run the main.phpfile above, it’s executed as we would expect. If we delete the file however, the interpreter will raise a fatal error, and all execution will stop.

Output: missing file2.php

Warning: require(C:\xampp\htdocs\PHPProjects\file2.php): failed to open stream: No such file or directory on line 3Fatal error: require(): Failed opening required 'file2.php' (include_path='C:\xampp\php\PEAR') on line 3

How to include_once or require_once

In some cases, a file may accidentally be included or required more than once. The interpreter would parse the file again, which would cause problems such as variable reassignments or function redefinitions.

PHP provides us with the include_onceand require_oncestatements to help avoid such cases. When we use these, the interpreter will not include, or require, a file that has already been included or required.

Syntax: include_once

 include_once 'filename.php';

Syntax: require_once

 require_once 'filename.php';

Example:

<?phpif (include_once "file2.php") { echo "file2.php has already been included.<br>";}echo $fruit[0];?>

Summary: Points to remember

  • Include and require allows us to separate our code into multiple files. By including or requiring a file, we have access to its content.
  • To include or require a file we simply write the keyword followed by the path of the file.
  • We can tell the interpreter to include or require a file only once, avoiding any accidental double inclusions.
PreviousFunctionsNextForm handling
PHP Include & Require files Tutorial | KoderHQ (2024)

References

Top Articles
Homemade mascara: All Natural and Eye-Friendly
Cómo hacer pollo frito vegano (Estilo KFC) | Hazlo Vegan
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
12 30 Pacific Time
Jami Lafay Gofundme
Greenbrier Bunker Tour Coupon
No Compromise in Maneuverability and Effectiveness
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Francesca Jacobs Ret

Last Updated:

Views: 6361

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Francesca Jacobs Ret

Birthday: 1996-12-09

Address: Apt. 141 1406 Mitch Summit, New Teganshire, UT 82655-0699

Phone: +2296092334654

Job: Technology Architect

Hobby: Snowboarding, Scouting, Foreign language learning, Dowsing, Baton twirling, Sculpting, Cabaret

Introduction: My name is Francesca Jacobs Ret, I am a innocent, super, beautiful, charming, lucky, gentle, clever person who loves writing and wants to share my knowledge and understanding with you.