Pin Me

Tips for Using PHP Includes

written by: Strobe•edited by: Michele McDonough•updated: 6/30/2011

By using PHP includes in your PHP scripts you can greatly increase your productivity. By using PHP includes, you can also make template files, and make updating your website incredibly easy.

  • slide 1 of 1

    If you’ve ever done any sort of programming before, you know how mundane it can be to code the same thing over and over again. Even when designing websites with HTML, if you make each individual page and need to change just one small detail, you’ve got a lot of files just to edit one small thing. PHP Includes can help you with this problem and save you a lot of time when coding PHP.

    Including files using PHP is pretty straight forward, you would use the include function listed below:

    <? include(“myfile.php”); ?>

    Now, when your code is executed, and the interpreter gets to this line, it will substitute the results of the include function and stick that code or text in the script. So it would be just like typing the contents of myfile.php into your program. Note that you can use a full path to the file if it's not in the same folder. The PHP include function can be used with text, php, inc, or any other file. As long as the file is text based.

    How can PHP Includes be helpful?

    When making a PHP script, you may create different spots in the script that need to access the same file again and again. Instead of typing the contents of the file, simply use the PHP include function in the PHP script to access the file. This way if you were to find an error in the file, you can change the file and not need to change it anywhere else.

    Another way PHP includes are helpful is when designing a website. When you’re developing a website, it may span from just a few pages to many thousands. Now, if you ever decided you wanted to change something on the many thousand pages website, you would not want to change ever single file. By correctly using PHP includes, you can make the website with header, footer, and template files. So, when updating the website, if you wanted to edit the logo or the site, you would just need to edit the header file. All the pages that have the header file included would then be updated with the new file.

    Another form of including files in a PHP script is the require function, although very much like the PHP include function. The require function, actually requires the file or the PHP script will throw a fatal error and stop execution. The PHP include function will only throw a warning when the file is unavailable.

    Using PHP includes can speed up your coding time tremendously. And it makes updating your code and website a breeze. Even if you don’t know PHP very well at all, you can make a website template and use PHP includes in it even if it’s only HTML files.