views:

1310

answers:

3

Hi All,

I'm trying to create a script to extract the variables from a file on the same server.

The problem is, I don't know what else is going to be in the file all of the time (the script is for other people to use), so I don't really want to load all of the contents or execute any of the code.

I've thought of using file_get_contents rather than anything like require or include, but I'm stuck... is there a way to parse all of the variables within the string? Alternatively, is there a "safe" way to include files?

Many thanks, James

+2  A: 

Why don't you put all the variables in a third file, then include them in the other two files?

What you are trying to do sounds dangerous, especially if by "for other people to use" you mean others can write those files.

Marius
My script is trying to add functionality to existing systems. Typically these files should only contain variables, but I'm very weary. I also don't want to include lots of useless variables that I don't need into my script.Ideally this needs to be a "plug-and-play" kind of application, so I can't really ask the users to change their apps.
+1  A: 

In this case, you don't want your users editing a PHP file at all. As you've pointed out, you cannot include() the file if you cannot trust its contents. Since you can't execute the file as PHP, there's no advantage to the file even being PHP, so you can choose a format that your own script can more readily read. For example, with the parse_ini_file function you can easily read configuration values from a .ini file.

If it absolutely has to be a PHP file, you might have to attempt to parse it by hand. If you can demand that the file be a subset of PHP (e.g., that it include nothing but variable declarations) that sounds feasible, albeit still very hackish. If the file can legitimately be a completely functional PHP script, in which some variables happen to be defined, it's probably time to rethink the architecture entirely.

VoteyDisciple
+1  A: 

file_get_contents + preg_match

You'll need some crafty regex to go along with it.

whichdan