Get variables from another PHP file without executing code?

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

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

I was thinking about using file_get_contents rather than something like require or include, but I'm stuck ... is there a way to parse all the variables in a line? Also, is there a "safe" way to include files?

Thanks a lot James

+2


source to share


4 answers


file_get_contents + preg_match



You will need some clever regex to agree with it.

+3


source


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



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

+2


source


You should try php tokenizer .

+2


source


In this case, you don't want your users to edit the PHP file at all. As you already pointed out, you cannot a include()

file if you cannot trust its contents. Since you cannot execute the file as PHP, there is no advantage to the file even being PHP, so you can choose a format that your own script can more easily read. For example, with a function, parse_ini_file

you can read the configuration values ​​from a file easily .ini

.

If it absolutely has to be a PHP file, you might have to try to parse it manually. If you can require this file to be a subset of PHP (for example, it only includes variable declarations), it seems possible, albeit very hacky. If a file can legitimately be a fully functional PHP script in which some variables are defined, it might be time to completely rethink the architecture.

+1


source







All Articles