Skip to content

Instantly share code, notes, and snippets.

@staabm
Last active July 30, 2020 14:16
Show Gist options
  • Save staabm/3740b00e7c2eca2b5adc to your computer and use it in GitHub Desktop.
Save staabm/3740b00e7c2eca2b5adc to your computer and use it in GitHub Desktop.
Throw error when post_max_size was reached
<?php
function checkPostSizeExceeded() {
$maxPostSize = iniGetBytes('post_max_size');
if ($_SERVER['CONTENT_LENGTH'] > $maxPostSize) {
throw new Exception(
sprintf('Max post size exceeded! Got %s bytes, but limit is %s bytes.',
$_SERVER['CONTENT_LENGTH'],
$maxPostSize
)
);
} else if ($_SERVER['HTTP_TRANSFER_ENCODING'] == 'chunked') {
$fh = @fopen('php://input', 'r');
if ($fh)
{
$postsize = 0;
while (!feof($fh))
{
$s = fread($fh, 8096);
if ($s !== false)
{
$postsize += strlen($s);
if ($postsize > $maxPostSize) {
throw new Exception(
sprintf('Max post size exceeded! Limit is %s bytes.',
$maxPostSize
)
);
}
}
}
fclose($fh);
}
}
}
function iniGetBytes($val)
{
$val = trim(ini_get($val));
if ($val != '') {
$last = strtolower(
$val{strlen($val) - 1}
);
} else {
$last = '';
}
switch ($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment