Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active August 24, 2019 19:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/5649b3ff8533e09a546de403f3f28fc0 to your computer and use it in GitHub Desktop.
Save ziadoz/5649b3ff8533e09a546de403f3f28fc0 to your computer and use it in GitHub Desktop.
Prevent Variable Leakage In PHP Includes
<?php
// Use a closure so nothing leaks out when included.
return (function () {
$array = ['foo', 'bar'];
foreach ($array as $string) {
// Some exciting logic.
}
return 'FOOBAR';
})();
<?php
// The standard leaky include.
$array = ['foo', 'bar'];
foreach ($array as $string) {
// Some exciting logic.
}
return 'FOOBAR';
<?php
$array = ['foo', 'bar'];
foreach ($array as $string) {
// Some exciting logic.
}
unset($array, $string); // Unset variables so nothing leaks out when included.
return 'FOOBAR';
<?php
$returned = include __DIR__ . '/include-me-unset.php';
echo (isset($array) ? '$array variable is set' : '$array variable is not set') . PHP_EOL;
echo (isset($string) ? '$string variable is set' : '$string variable is not set') . PHP_EOL;
echo '$returned is ' . $returned . PHP_EOL;
$returned = include __DIR__ . '/include-me-func.php';
echo (isset($array) ? '$array variable is set' : '$array variable is not set') . PHP_EOL;
echo (isset($string) ? '$string variable is set' : '$string variable is not set') . PHP_EOL;
echo '$returned is ' . $returned . PHP_EOL;
$returned = (function () { return include __DIR__ . '/include-me-leaky.php'; })();
echo (isset($array) ? '$array variable is set' : '$array variable is not set') . PHP_EOL;
echo (isset($string) ? '$string variable is set' : '$string variable is not set') . PHP_EOL;
echo '$returned is ' . $returned . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment