Including Files in PHP − Beginner Tutorial

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

All righ...
PHP Help: Including Files in PHP − Beginner Tutorial


                                                    Table of Conten...
Including Files in PHP − Beginner Tutorial
Navigate: PHP Tutorials > PHP > Basics & Beginner Tutorials


Author: phpfreak
...
PHP Help: Including Files in PHP − Beginner Tutorial

The include() Construct


The include() constrcut is the most common...
PHP Help: Including Files in PHP − Beginner Tutorial
<?php
require($_SERVER['DOCUMENT_ROOT'].'/myfile.php');
?>




The re...
PHP Help: Including Files in PHP − Beginner Tutorial
?>




Using Shortucts or Working Directory Paths


If you are famili...
PHP Help: Including Files in PHP − Beginner Tutorial

Smart Development − Command Line and Web Interface Applications


If...
PHP Help: Including Files in PHP − Beginner Tutorial

Including NON−PHP Files


If you include a file, for example a plain...
PHP Help: Including Files in PHP − Beginner Tutorial



I am positive some people will say this does not matter, however i...
Including-Files-in-PHP---Beginner-Tutorial
Upcoming SlideShare
Loading in...5
×

Including-Files-in-PHP---Beginner-Tutorial

578

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
578
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Including-Files-in-PHP---Beginner-Tutorial"

  1. 1. 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
  2. 2. PHP Help: Including Files in PHP − Beginner Tutorial Table of Contents Including Files in PHP − Beginner Tutorial.....................................................................................................1 Introduction to Including Files in PHP....................................................................................................1 The Core PHP Constructs for Including Files.........................................................................................1 The include() Construct.....................................................................................................................2 The include_once() Construct...........................................................................................................2 The require() Construct.....................................................................................................................2 The require_once() Construct ...........................................................................................................3 . Understanding Paths................................................................................................................................3 Using Shortucts or Working Directory Paths....................................................................................4 Smart Development − Command Line and Web Interface Applications ..........................................5 Permissions on Included Files.................................................................................................................5 PHP Include File Security ........................................................................................................................5 Including NON−PHP Files ................................................................................................................6 The Worst Mistake............................................................................................................................6 Notes On Open Base Directory (open_basedir) and Safe Mode.............................................................7 Summary..................................................................................................................................................7 i
  3. 3. Including Files in PHP − Beginner Tutorial Navigate: PHP Tutorials > PHP > Basics & Beginner Tutorials Author: phpfreak Date: 04/05/2005 Version 1.0 Experience 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 an intermediate or slightly beyond user, this tutorial may benefit you in some way because we are going to discuss some security features. The main purpose of this tutorial is to kick off the new "Beginner" series of PHP tutorials. These tutorials will cover many of the common problems and questions, or misconceptions that we have seen on our forums and throughout the net regarding PHP. This tutorial will be fairly short, so even if you've been working with PHP for 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 users how to include files properly. The constructs we will discuss in this tutorial should be used when you want to pull together pieces of code or settings for your project. A common scenario would be a group of functions that you use throughout a website, or a class, or even a group of configuration settings, stored in a file such as a config.php with your site's pertinent information. I would like to point out the fact that we are referring to constructs in this tutorial. Many people still consider these particular constructs as functions, however that is incorrect and we are going to refer to them the proper way, 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 create code in separate files and then be able to use that code to include functions, variables and etc, in other PHP scripts. You have two main options. To include() a file or to require() a file. We'll get into the specifics in a moment and you'll quickly understand what the differences are. Including Files in PHP − Beginner Tutorial 1
  4. 4. PHP Help: Including Files in PHP − Beginner Tutorial The include() Construct The include() constrcut is the most commonly used method to include files amongst most developers. It's purpose is to simply include a file and that's it. If the file does not exist, it will return a warning and still allow the script that's trying to include the file to continue to operate even if the warning is issued. Here's a common example: PHP Example: <?php include($_SERVER['DOCUMENT_ROOT'].'/myfile.php'); ?> Now, all of the code, and functions from myfile.php will be available throughout the rest of the current PHP script 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 the relationships 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 has already been included in this code execution, it will not be included again. This is a good method to use and I would recommend it above using the standard include() construct because it can prevent you from redeclaring functions that you may have already included previously. As your code becomes more complex, you may have 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 the preference for construct of choice! PHP Example: <?php include_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 be included, a Fatal Error will be produced and the execution of the PHP script will be halted! This construct is important for those applications you may develop that have dependancies from other files which must be met in order for your script to function properly. PHP Example: The include() Construct 2
  5. 5. PHP Help: Including Files in PHP − Beginner Tutorial <?php require($_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 into account 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 this instance. In addition, a Fatal Error will be produced just like the require() construct does if the file cannot be read or included. PHP Example: <?php require_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 website on your local machine and you define the full path of the included files, you may run into problems on the live server 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 web server 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. His Document Root is C:mywebpublic_html . When Jeff includes a file, he uses a piece of code like this: PHP Example: <?php require_once('C:mywebpublic_htmlmyfile.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 Jeff would have used the proper superglobal to include his file, this code would be portable and also work both on Windows and Linux. In addition, Jeff's code may also work if he moves to a different Web Hosting company and his Document Root should change. He can simply upload these files anywhere as long as he preserves the same Document Root workspace. Here's an example: PHP Example: <?php require_once($_SERVER['DOCUMENT_ROOT'].'/myfile.php'); The require() Construct 3
  6. 6. PHP Help: Including Files in PHP − Beginner Tutorial ?> 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 use those as well. However, I will give you my recommendation: Don't use this method! I prefer using the appropriate 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 the file he's working on. He can simply use the following code to include the file: PHP Example: <?php require_once('myfile.php'); ?> Additionally, if Jeff wants to go back to the Document Root, he can use: PHP Example: <?php require_once('./myfile.php'); ?> If Jeff knows his file is up one directory he can use: PHP Example: <?php require_once('../myfile.php'); ?> If Jeff wants to include a file inside the subdirectory includes he can use: PHP Example: <?php require_once('includes/myfile.php'); ?> In the previous example, any of the other code exmaples will work as well. Such as: ./includes/myfile.php and etc. As long as you know how to navigate with CD commands from the local directory your PHP script is that you are including the files into, you can use those paths. Understanding Paths 4
  7. 7. PHP Help: Including Files in PHP − Beginner Tutorial 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, you must take into consideration that the DOCUMENT_ROOT key is not available in the $_SERVER supergobal array. Therefore, you must overcome this and believe it or not, it's very easy. Once again, I believe in portability, 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 a function 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() function and the __FILE__ constant. The output would be exactly the same as $_SERVER['DOCUMENT_ROOT'] if you were running the same script through the web server. Once again, if you keep everything under a working directory and you always include files and execute the file under the working directory, you can bypass using these tricks and use your shortcuts. However, I advise you do things this way to ensure that your code is portable 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 be included do not have to have execute permissions on the web servers. Simple READ permissions is all that is needed by the server. In our Web Hosting business, one of the common things we see users do is attempt to CHMOD the include files 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 many times by inexperienced developers. Smart Development − Command Line and Web Interface Applications 5
  8. 8. PHP Help: Including Files in PHP − Beginner Tutorial 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 will be displayed within the current PHP script. For example, a style sheet, or your password files, or any files that do can display it's contents by accessing it via your web browser. This creates a great security risk if you are not 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 a file, such as a cool style sheet or something to that affect. All a malicious user has to do is pass along the file of 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 before the $_GET['css_file'] portion of your include argument, the user can still pass in a semicolon and play with your 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 is create a remote HTML form, or even use cURL to replicate the form and post to your script. Including NON−PHP Files 6
  9. 9. PHP Help: Including Files in PHP − Beginner Tutorial I am positive some people will say this does not matter, however it could, depending on the rest of your script and how it handles the information after the script has been included. As a side note, a few functions you definately 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 Safe Mode Many Web Hosting companies nowadays are enforcing a great security feature called open_basedir. This feature is designed to prevent users from accessing files outside of their allowed directories. For example, you cannot access another user's home directory, or anything outside of your home directory. If you attempt to access 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, the purpose of including files is to access code from another file within the file you are working. It can be very secure, 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 those completely different features. If anyone has something to add, please post a comment below. We'll update the tutorial as this will probably become a reference for many questions to come in the future. Good luck with your development! −phpfreak © Copyright 2002 − 2005 The Web Freaks, INC. The Worst Mistake 7

×