1. Home
  2. Computing & Technology
  3. PHP / MySQL

Including External Files in PHP

By , About.com Guide

2 of 3

Pulling The File

First let's create a file that will hold our variables. Let's call it variables.php

<?php
//variables.php
$name = 'Loretta';
$age = '27';
?>

Now we will include this file into our second file called report.php

<?php
//report.php
include 'variables.php';
// or you can use the full path; include 'http://www.yoursite.com/folder/folder2/variables.php';
print $name . " is my name and I am " . $age . " years old.";
?>

As you can see, the print command easily uses these variables. You can also call the include within a function but we must declare the variables to be GLOBAL if we want to use them outside the function:

<?php
function printname ()
{
global $name;
include 'variables.php';
print $name . " is my name and I am " . $age . " years old.";
}
printname ();
print "<br>";
//The line below will work because $name is GLOBAL
print "I like my name, " . $name;
print "<br>";
//The next line will NOT work because $age is NOT defined as global
print "I like being " . $age . " years old.";
?>

Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL

©2009 About.com, a part of The New York Times Company.

All rights reserved.