DJ Mike's Tutorials: PHP

Working With Files


< ^ >

include()

One of the most useful functions is the include() statement. Include() lets you save a block of text or code that you want to use on more than one page as a single file and insert that file into a web page. For example, the footer for this page and all the other pages is at http://eclecticdjs.com/mike/tutorials/bottom.txt. To add all that to the bottom of this page, I use just a single line of code:



<? include("../bottom.txt"); ?>


For the example above, the included file is a .txt file. Included files are displayed as HTML by default so if you want to run PHP code in the included file, the PHP code must be enclosed in PHP start and end tags. Storing your included files as .txt can be a security problem. If you have passwords to validate a login form and someone guesses the file name, the can see your passwords. If you have sensitive information, save the file as .php and have the sensitive information in PHP code. Otherwise, it doesn't matter what extension you use. Included files a are commonly given a .inc extension.

Include() can be used with conditional statements so the file is only included when certain conditions are met. For example, I have a file at http://eclecticdjs.com/mike/wtv/tools/calendar.php that makes a calendar. If I want to use that function on this page but only when a password is submitted, I can use this form and PHP code:



<?
$pass 
$_POST[pass];
if ( 
$pass == \"calendar")
{
include(
"../../wtv/tools/calendar.php");
}
?>


When the correct password, calendar, is submitted, the file calendar_function.php is included and the function make_calendar() is called from it.



If you have a lot of useful user defined functions, you can put them all in one file, include that file in every page and call any of the functions where ever you want.

require()

require() works just like include() with one difference. If include() can't find the file, you just get a warning thet the file is not found. If require() can't find the file, the script dies.




< ^ >



Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>