Is there a way to use unserialize
with a memory/size limit?
Currently we have:
$data = unserialize($_SESSION['visits']);
and we occasionally get:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 17645568 bytes) in Unknown on line 0
when a visitor has had a lot of visits in a short period of time (session value stores information about each page visited).
If the length of $_SESSION['visits']
is above a million characters it causes the issue so I can do a simple check on that but is there a better solution than this:
if(strlen($_SESSION['visits']) <= 1000000) {
$data = unserialize($_SESSION['visits']);
} else {
$data = array();
}
I thought try catch
might behave better but it didn't get caught:
try{
$data = unserialize($_SESSION['vists']);
} catch(\Exception $exception){
error_log('Caught memory limit');
}
The answer to this question is not to increase the memory size.
There are two options:
Which can fail with memory limit error and possibly return back only the data you are interested in.
How?
$argv
exec()
to address the question requirement, you can:
Like https://github.com/xKerman/restricted-unserialize , which allows:
The two options above are solution to your requirement. However my strong advise is to store the session/visits data in a database and then store only an unique id to them.
The most memory efficient you'll get is probably by storing everything in a string, packed in binary, and use manual indexing to it.And for this you can make use of pack()
method.
Memory Usage Differences
$a = memory_get_usage();
$data = serialize(array(1 => 1, 0 => 2, 3 => 3));
$b = memory_get_usage();
$c = $b - $a;
echo $c; //Outputs 296
And when same data packed in the form of binary string.
$a = memory_get_usage();
$data = pack("C*",array(1 => 1, 0 => 2, 3 => 3));
$b = memory_get_usage();
$c = $b - $a;
echo $c; //Outputs 72
Saves your memory a lot more than expected and is very efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With