Correct file paths when using include statements

This basic script is in a folder off of the root called campaigns. The sponsorLookup.php is a file on the root. The print statement for SponsorFirstName is failing while the fakeSponsor print statement works fine. The only difference between the two included files is that one is on the root and the other is in the campaigns folder. When you want to reference a file that is up one level, you put a / in front of it, right? I’ve even tried using the full path (http://www.example.com/sponsorLookup.php) and that doesn’t work either.

Thanks!


<?php
include 'startSession.php';
$_SESSION[sponsorID] = 121;

include '/sponsorLookup.php';
include 'fakeSponsor.php';

print ("<p>SponsorFirstName is $_SESSION[sponsorFirstName]</p>");
print ("<p>fakeSponsor is $fakeSponsor");

?>

If you want to include something from “one level up” you would use “…/”. If you use “/” then it will look in the root of your servers HDD.

Also make sure you use quotes when accessing keys in an array. You may want to try and access the sponsorFirstName as such:


print ("<p>SponsorFirstName is {$_SESSION['sponsorFirstName']}</p>");

Note the single quotes around the key name. The curly braces “{}” around the variable aren’t always needed, but it helps give PHP a “hint” than the enclosed is a PHP variable.

Also note that array keys are case sensitive. In your post you refer to the key as SponsorFirstName while in your script you call it as sponsorFirstName.

Not quiet. It will look in the Document_Root of your website. Not the root of your HDD.

start your php script with:

$path = '/absolute/path/to/document/root/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

and do your includes like this:

include('includes/functions.php');

assuming that ‘includes’ folder is in the root dir from $path

You might as well do this:

$path = '/absolute/path/to/document/root/'.PATH_SEPARATOR.'/absolute/path/to/document/root/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

and include like this:

include('functions.php');

No more headbreaking …/…/blabla/somescript.php or things like that.
Look in the php manual for the set_include_path() function.

So what would happen if they included their files like “/somefile.php”?

That depends on how the include path is set. With or without trailing /