From 047f2617f164f8f95d1c576994008719af68fecb Mon Sep 17 00:00:00 2001 From: Joey3000 Date: Sun, 14 Feb 2016 13:40:58 +0100 Subject: [PATCH] Circular reference handling improvement Refs https://github.com/phpseclib/phpseclib/pull/934/files#r52838650 This does the following: * Addresses the comments to https://github.com/terrafrost/phpseclib/commit/102d53bd275f5c08e7042eaac5fb74f73eded62a * Fixes an "Allowed memory size of ... bytes exhausted" issue and simplifies the implementation, bringing it closer to the example in https://stackoverflow.com/questions/9042142/detecting-infinite-array-recursion-in-php/9293146#9293146 --- phpseclib/Crypt/Random.php | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/phpseclib/Crypt/Random.php b/phpseclib/Crypt/Random.php index 9f2487cb..46a441ec 100644 --- a/phpseclib/Crypt/Random.php +++ b/phpseclib/Crypt/Random.php @@ -268,7 +268,6 @@ if (!function_exists('phpseclib_safe_serialize')) { * PHP 5.3 will emit a warning. * * @param mixed $arr - * @param array $refs optional * @access public */ function phpseclib_safe_serialize(&$arr) @@ -280,20 +279,16 @@ if (!function_exists('phpseclib_safe_serialize')) { return serialize($arr); } $safearr = array(); - $unset = false; - if (!isset($arr['__phpseclib_marker'])) { - $unset = true; - $arr['__phpseclib_marker'] = true; - } + $arr['__phpseclib_marker'] = true; foreach (array_keys($arr) as $key) { - if (is_object($arr[$key]) || $key == '__phpseclib_marker') { - continue; + // do not recurse on: + // - the '__phpseclib_marker' key itself + // - a circular reference (marked with that key) + if ($key !== '__phpseclib_marker' && !isset($arr[$key]['__phpseclib_marker'])) { + $safearr[$key] = is_array($arr[$key]) ? phpseclib_safe_serialize($arr[$key]) : $arr[$key]; } - $safearr[$key] = is_array($arr[$key]) ? phpseclib_safe_serialize($arr[$key], $refs) : $arr[$key]; - } - if ($unset) { - unset($arr['__phpseclib_marker']); } + unset($arr['__phpseclib_marker']); return serialize($safearr); } }