Using PHP code to load further PHP code from a file

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
bones
Forum Newbie
Posts: 2
Joined: Sat Apr 24, 2010 3:56 am

Using PHP code to load further PHP code from a file

Post by bones »

Hi,

I new to the whole concept of php and i want to build a dynamic web page.
I'm using conditional coding to load external files containing html and php code.
I would load the file into an array and then echo the array. This works fine for
the html code in the file but, the php code just gets ignored by the server.
e.g.
The file test.php contains the following:
<h1> Hello World </h1><br>
<?php echo 'Hello World' ?>


this is an extract of index.php :
$file_1 = '/var/www/test.php';
$data_1 = file_get_contents($file_1);
echo $data_1;


then both
Hello World
and
<?php echo 'Hello World' ?>

gets passed to the browser without the php code being parsed to the server.
Any Ideas?

Thanks
User avatar
Zyxist
Forum Contributor
Posts: 104
Joined: Sun Jan 14, 2007 10:44 am
Location: Cracow, Poland

Re: Using PHP code to load further PHP code from a file

Post by Zyxist »

As far as I've understood your problem, you can simply do:

Code: Select all

include '/var/www/test.php';
This will handle both fully static files and files with PHP code snippets and is the simplest and most effective way. Note that if you are going to read a file name from an URL or HTML form, you have to secure it against various attacks. Otherwise such script would be extremely dangerous.

PS. file_get_contents() does not produce any array, but just a string with the file content.
bones
Forum Newbie
Posts: 2
Joined: Sat Apr 24, 2010 3:56 am

Re: Using PHP code to load further PHP code from a file

Post by bones »

Thanks that solved my problem 100%!
Also thanks for the advice on the security, I'll have to look up on that.
Post Reply