Php using variables in include function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
int3rc3ptor
Forum Newbie
Posts: 2
Joined: Sun Feb 03, 2008 3:12 pm

Php using variables in include function

Post by int3rc3ptor »

Hi

Sorry bit of a newbie here, I'm looking to declare a variable and then pass that variable into the include function.

Say for example I have an index page, which then links to various page, but those various pages use the same template.

The link carries a variable like page=test

So the template page loads and because I like to keep content separate from presentation given what I'm working on is a CMS solution is ideally something like this.

$test = $_GET['page'];
include "/images/" .$test. ".gif";

Does this make sense? I'm trying to use a variable as part of the include declaration, but being a newbie, I don't see to have hit the nail on the head yet.

Any help would be appreciated

Regards

Int3rc3ptor
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Php using variables in include function

Post by Christopher »

I would recommend something like this:

Code: Select all

// remove any characters you do not want
$test = preg_replace('/[^a-zA-Z0-9\_]/', '', $_GET['page']);
// check the docs about absolute and relative paths, and how the include_path works
include $Config['PATH'] . "/images/" . $test . ".gif";
(#10850)
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Php using variables in include function

Post by Jonah Bron »

$_GET is a super-global variable. It can be used in the included file without being defined.

Code: Select all

//INDEX.PHP
include('FILE.PHP');

Code: Select all

//FILE.PHP
echo $_GET['page'];
int3rc3ptor
Forum Newbie
Posts: 2
Joined: Sun Feb 03, 2008 3:12 pm

Re: Php using variables in include function

Post by int3rc3ptor »

Cheers Chaps

I'll certainly give both a try

Thank You!!

int3rc3ptor
Post Reply