Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require an arbitrary PHP file without leaking variables into scope

Is it possible in PHP to require an arbitrary file without leaking any variables from the current scope into the required file's variable namespace or polluting the global variable scope?

I'm wanting to do lightweight templating with PHP files and was wondering for purity sake if it was possible to load a template file without any variables in it's scope but the intended ones.

I have setup a test that I would like a solution to pass. It should beable to require RequiredFile.php and have it return Success, no leaking variables..

RequiredFile.php:

<?php  print array() === get_defined_vars()     ? "Success, no leaking variables."     : "Failed, leaked variables: ".implode(", ",array_keys(get_defined_vars()));  ?> 

The closest I've gotten was using a closure, but it still returns Failed, leaked variables: _file.

$scope = function( $_file, array $scope_variables ) {     extract( $scope_variables ); unset( $scope_variables );     //No way to prevent $_file from leaking since it's used in the require call     require( $_file ); }; $scope( "RequiredFile.php", array() ); 

Any ideas?

like image 996
Kendall Hopkins Avatar asked Nov 09 '11 01:11

Kendall Hopkins


People also ask

Are PHP variables scoped?

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local.

What are the 4 variable scopes of PHP?

PHP has four types of variable scopes including local, global, static, and function parameters.

What are supported scopes for variables in PHP?

PHP has three types of variable scopes: Local variable. Global variable. Static variable.


1 Answers

Look at this:

$scope = function() {     // It's very simple :)     extract(func_get_arg(1));     require func_get_arg(0); }; $scope("RequiredFile.php", []); 
like image 118
lisachenko Avatar answered Sep 22 '22 22:09

lisachenko