including files in php beginner tutorial

10
Including Files in PHP - Beginner Tutorial Copyright Notice © 2002 - 2005 - The Web Freaks, INC, PHP Freaks.com All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the written permission of the publisher. Products that are referred to in this document may be either trademarks and/or registered trademarks of the respective owners. The publisher and the author make no claim to these trademarks. While every precaution has been taken in the preparation of this document, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of information contained in this document or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or indirectly by this document. Last Update: Tue, 05 Apr 2005 23:37:15 -0400

Upload: doankhue

Post on 08-Dec-2016

217 views

Category:

Documents


1 download

TRANSCRIPT

Including Files in PHP − Beginner Tutorial

Copyright Notice

© 2002 − 2005 − The Web Freaks, INC, PHP Freaks.com

All rights reserved. No parts of this work may be reproduced in any form or by any means − graphic,electronic, or mechanical, including photocopying, recording, taping, or information storage and retrievalsystems − without the written permission of the publisher.

Products that are referred to in this document may be either trademarks and/or registered trademarks of therespective owners. The publisher and the author make no claim to these trademarks.

While every precaution has been taken in the preparation of this document, the publisher and the authorassume no responsibility for errors or omissions, or for damages resulting from the use of informationcontained in this document or from the use of programs and source code that may accompany it. In no eventshall the publisher and the author be liable for any loss of profit or any other commercial damage caused oralleged to have been caused directly or indirectly by this document.

Last Update: Tue, 05 Apr 2005 23:37:15 −0400

Table of ContentsIncluding Files in PHP − Beginner Tutorial.....................................................................................................1

Introduction to Including Files in PHP....................................................................................................1The Core PHP Constructs for Including Files.........................................................................................1

The include() Construct.....................................................................................................................2The include_once() Construct...........................................................................................................2The require() Construct.....................................................................................................................2The require_once() Construct............................................................................................................3

Understanding Paths................................................................................................................................3Using Shortucts or Working Directory Paths....................................................................................4Smart Development − Command Line and Web Interface Applications..........................................5

Permissions on Included Files.................................................................................................................5PHP Include File Security........................................................................................................................5

Including NON−PHP Files................................................................................................................6The Worst Mistake............................................................................................................................6

Notes On Open Base Directory (open_basedir) and Safe Mode.............................................................7Summary..................................................................................................................................................7

PHP Help: Including Files in PHP − Beginner Tutorial

i

Including Files in PHP − Beginner TutorialNavigate: PHP Tutorials > PHP > Basics & Beginner Tutorials

Author: phpfreakDate: 04/05/2005Version 1.0Experience Level: Beginner

Introduction to Including Files in PHP

First, I want to say this is a beginner tutorial on including files with PHP. However, even if you are anintermediate or slightly beyond user, this tutorial may benefit you in some way because we are going todiscuss some security features.

The main purpose of this tutorial is to kick off the new "Beginner" series of PHP tutorials. These tutorials willcover many of the common problems and questions, or misconceptions that we have seen on our forums andthroughout the net regarding PHP. This tutorial will be fairly short, so even if you've been working with PHPfor a while, you may still want to read on.

In addition, this tutorial is not written to read or write to other files. It is simply written to show new usershow to include files properly.

The constructs we will discuss in this tutorial should be used when you want to pull together pieces of code orsettings for your project. A common scenario would be a group of functions that you use throughout awebsite, or a class, or even a group of configuration settings, stored in a file such as a config.php with yoursite's pertinent information.

I would like to point out the fact that we are referring to constructs in this tutorial. Many people still considerthese particular constructs as functions, however that is incorrect and we are going to refer to them the properway, which is indeed a construct.

The Core PHP Constructs for Including Files

There are four core constructs for including files into your PHP scripts. The main objective is for you to createcode in separate files and then be able to use that code to include functions, variables and etc, in other PHPscripts. You have two main options. To include() a file or to require() a file. We'll get into the specifics in amoment and you'll quickly understand what the differences are.

Including Files in PHP − Beginner Tutorial 1

The include() Construct

The include() constrcut is the most commonly used method to include files amongst most developers. It'spurpose is to simply include a file and that's it. If the file does not exist, it will return a warning and still allowthe script that's trying to include the file to continue to operate even if the warning is issued. Here's a commonexample:

PHP Example:

<?phpinclude($_SERVER['DOCUMENT_ROOT'].'/myfile.php');?>

Now, all of the code, and functions from myfile.php will be available throughout the rest of the current PHPscript for use with the rest of your code.

Don't worry if you do not understand the paths used int he previous example yet, we'll get into therelationships between the current working directory and the filesystem later in this tutorial.

The include_once() Construct

Ok, the main difference between the include_once() construct and the include() construct is that if the file hasalready been included in this code execution, it will not be included again. This is a good method to use and Iwould recommend it above using the standard include() construct because it can prevent you from redeclaringfunctions that you may have already included previously. As your code becomes more complex, you mayhave files included in different files and when calling those files, you may start running into problems.

My recommendation: if you need to include a file using one of the include methods, use include_once() as thepreference for construct of choice!

PHP Example:

<?phpinclude_once($_SERVER['DOCUMENT_ROOT'].'/myfile.php');?>

The require() Construct

The require() construct is the same as include, but one major difference. If the file does not exist, or cannot beincluded, a Fatal Error will be produced and the execution of the PHP script will be halted! This construct isimportant for those applications you may develop that have dependancies from other files which must be metin order for your script to function properly.

PHP Example:

PHP Help: Including Files in PHP − Beginner Tutorial

The include() Construct 2

<?phprequire($_SERVER['DOCUMENT_ROOT'].'/myfile.php');?>

The require_once() Construct

This construct is the one that I use more than the other three. Personally, I feel that this construct takes intoaccount all of the necessary reasons you would be including a file in the first place. Just like include_once()the require_once() construct determines if the file has already been included and if it has been, it will skip thisinstance. In addition, a Fatal Error will be produced just like the require() construct does if the file cannot beread or included.

PHP Example:

<?phprequire_once($_SERVER['DOCUMENT_ROOT'].'/myfile.php');?>

Understanding Paths

There's a few things I think all developers should consider. Mainly, portability! If you develop your websiteon your local machine and you define the full path of the included files, you may run into problems on the liveserver if your paths are different. The best way to overcome this is to use the$_SERVER['DOCUMENT_ROOT'] superglobal to refer to the DOCUMENT_ROOT that is set by the webserver environment variables or configuration.

Here's a common example:

Jeff is developing his website on his local machine. He uses Windows, Apache, MySQL and PHP. HisDocument Root is C:\myweb\public_html . When Jeff includes a file, he uses a piece of code like this:

PHP Example:

<?phprequire_once('C:\myweb\public_html\myfile.php');?>

When Jeff uploads his file to his hosting account, on a Linux server, his Document Root may be:/home/jeff/public_html and clearly you can see already that this is going to cause a problem! However, if Jeffwould have used the proper superglobal to include his file, this code would be portable and also work both onWindows and Linux. In addition, Jeff's code may also work if he moves to a different Web Hosting companyand his Document Root should change. He can simply upload these files anywhere as long as he preserves thesame Document Root workspace. Here's an example:

PHP Example:

<?phprequire_once($_SERVER['DOCUMENT_ROOT'].'/myfile.php');

PHP Help: Including Files in PHP − Beginner Tutorial

The require() Construct 3

?>

Using Shortucts or Working Directory Paths

If you are familiar with the file system and you know how local paths work, or shortcuts work, you may usethose as well. However, I will give you my recommendation: Don't use this method! I prefer using theappropriate paths as I have already described in this tutorial.

Let's take Jeff for example again. Jeff knows that the file he wants to include is in the same directory as thefile he's working on. He can simply use the following code to include the file:

PHP Example:

<?phprequire_once('myfile.php');?>

Additionally, if Jeff wants to go back to the Document Root, he can use:

PHP Example:

<?phprequire_once('./myfile.php');?>

If Jeff knows his file is up one directory he can use:

PHP Example:

<?phprequire_once('../myfile.php');?>

If Jeff wants to include a file inside the subdirectory includes he can use:

PHP Example:

<?phprequire_once('includes/myfile.php');?>

In the previous example, any of the other code exmaples will work as well. Such as: ./includes/myfile.php andetc. As long as you know how to navigate with CD commands from the local directory your PHP script is thatyou are including the files into, you can use those paths.

PHP Help: Including Files in PHP − Beginner Tutorial

Understanding Paths 4

Smart Development − Command Line and Web Interface Applications

If you are developing a script that you want to run on the command line as well as in your web browser, youmust take into consideration that the DOCUMENT_ROOT key is not available in the $_SERVER supergobalarray. Therefore, you must overcome this and believe it or not, it's very easy. Once again, I believe inportability, so this example will get you on the right track.

For making include files work properly on the command line AND on the web server, we're going to use afunction and a constants. The code will look like this:

PHP Example:

<?php$docroot = dirname(__FILE__).'/';require_once($docroot.'myfile.php');?>

The previous example will basically create a DOCUMENT_ROOT in $docroot using the dirname() functionand the __FILE__ constant. The output would be exactly the same as $_SERVER['DOCUMENT_ROOT'] ifyou were running the same script through the web server. Once again, if you keep everything under a workingdirectory and you always include files and execute the file under the working directory, you can bypass usingthese tricks and use your shortcuts. However, I advise you do things this way to ensure that your code isportable and will work under any circustmances.

Let's move along and discuss some security related issues with including files.

Permissions on Included Files

Including files is very easy, however a few other misconceptions are that unlike CGI scripts, the files to beincluded do not have to have execute permissions on the web servers. Simple READ permissions is all that isneeded by the server.

In our Web Hosting business, one of the common things we see users do is attempt to CHMOD the includefiles along with their PHP files to the maximum value (ie: 777) and so forth. Don't do this! It's not necessary!

PHP Include File Security

There are a few important security risks that come to mind when including files and I've seen them manytimes by inexperienced developers.

PHP Help: Including Files in PHP − Beginner Tutorial

Smart Development − Command Line and Web Interface Applications 5

Including NON−PHP Files

If you include a file, for example a plain text file that does not have the PHP open and close tags, the file willbe displayed within the current PHP script. For example, a style sheet, or your password files, or any files thatdo can display it's contents by accessing it via your web browser. This creates a great security risk if you arenot careful, which we will discuss next.

The Worst Mistake

This is the one rule I want to pass along to you and I hope that you remember this.

NEVER EVER include or read, execute, delete files based on USER INPUT.

What does that mean? It means never let a user specify which file, through a form $_POST, $_REQUEST or a$_GET method, and etc. Let's take this code for example.

The following code is BAD CODE EXAMPLE. PLEASE DO NOT USE IT!

PHP Example:<?php// My UNcool CSS include script.echo '<html>';echo '<head>';echo '<title>My Bad CSS Example</title>';

// Create a security hole!

include($_GET['css_file']);

// End security hole!

echo '</head>';// the rest.......?>

Ok, so let's say your script is named 'myfile.php' and you allow your users to pass in a querystring to include afile, such as a cool style sheet or something to that affect. All a malicious user has to do is pass along the fileof their choice and they can inject items into your variable scope. Here's an example:

http://yourdomain.com?css_file=/etc/shadow

Now, the /etc/shadow is in the file and that's not what you want to happen. Even if you define a path beforethe $_GET['css_file'] portion of your include argument, the user can still pass in a semicolon and play withyour file system. In general, this is just a bad idea.

Don't think that you can get away with using a $_POST or form to secure your page. All a hacker has to do iscreate a remote HTML form, or even use cURL to replicate the form and post to your script.

PHP Help: Including Files in PHP − Beginner Tutorial

Including NON−PHP Files 6

I am positive some people will say this does not matter, however it could, depending on the rest of your scriptand how it handles the information after the script has been included. As a side note, a few functions youdefinately want to prevent user input from are show_source(), higlight_file(), file_get_contents(), readfile(),fopen(), fpassthru(), exec(), shell_exec(), and any other function that can execute or read, display, copy,delete, and etc user inputs to the file system!

Notes On Open Base Directory (open_basedir) and SafeMode

Many Web Hosting companies nowadays are enforcing a great security feature called open_basedir. Thisfeature is designed to prevent users from accessing files outside of their allowed directories. For example, youcannot access another user's home directory, or anything outside of your home directory. If you attempt toaccess these files, you may get an error such as:

Warning: open_basedir restriction in effect. File is in wrong directory in /path/to/somefile.php on line 2

If the Web Hosting servers have Safe Mode enabled, open_basedir is enabled by default.

Note: WebHost Freaks does not use Safe Mode, but we do use open_basedir :)

Summary

This tutorial has covered just about all of the basics I can think of about including files. Remember, thepurpose of including files is to access code from another file within the file you are working. It can be verysecure, but only as secure as you develop it.

This tutorial was not written to teach you how to read or write files. Please do not base the topic on thosecompletely different features.

If anyone has something to add, please post a comment below. We'll update the tutorial as this will probablybecome a reference for many questions to come in the future.

Good luck with your development!−phpfreak

© Copyright 2002 − 2005 The Web Freaks, INC.

PHP Help: Including Files in PHP − Beginner Tutorial

The Worst Mistake 7