ServerParams.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form\Util;
  11. use Symfony\Component\HttpFoundation\RequestStack;
  12. /**
  13. * @author Bernhard Schussek <bschussek@gmail.com>
  14. */
  15. class ServerParams
  16. {
  17. private $requestStack;
  18. public function __construct(RequestStack $requestStack = null)
  19. {
  20. $this->requestStack = $requestStack;
  21. }
  22. /**
  23. * Returns true if the POST max size has been exceeded in the request.
  24. *
  25. * @return bool
  26. */
  27. public function hasPostMaxSizeBeenExceeded()
  28. {
  29. $contentLength = $this->getContentLength();
  30. $maxContentLength = $this->getPostMaxSize();
  31. return $maxContentLength && $contentLength > $maxContentLength;
  32. }
  33. /**
  34. * Returns maximum post size in bytes.
  35. *
  36. * @return int|null The maximum post size in bytes
  37. */
  38. public function getPostMaxSize()
  39. {
  40. $iniMax = strtolower($this->getNormalizedIniPostMaxSize());
  41. if ('' === $iniMax) {
  42. return null;
  43. }
  44. $max = ltrim($iniMax, '+');
  45. if (0 === strpos($max, '0x')) {
  46. $max = \intval($max, 16);
  47. } elseif (0 === strpos($max, '0')) {
  48. $max = \intval($max, 8);
  49. } else {
  50. $max = (int) $max;
  51. }
  52. switch (substr($iniMax, -1)) {
  53. case 't': $max *= 1024;
  54. // no break
  55. case 'g': $max *= 1024;
  56. // no break
  57. case 'm': $max *= 1024;
  58. // no break
  59. case 'k': $max *= 1024;
  60. }
  61. return $max;
  62. }
  63. /**
  64. * Returns the normalized "post_max_size" ini setting.
  65. *
  66. * @return string
  67. */
  68. public function getNormalizedIniPostMaxSize()
  69. {
  70. return strtoupper(trim(ini_get('post_max_size')));
  71. }
  72. /**
  73. * Returns the content length of the request.
  74. *
  75. * @return mixed The request content length
  76. */
  77. public function getContentLength()
  78. {
  79. if (null !== $this->requestStack && null !== $request = $this->requestStack->getCurrentRequest()) {
  80. return $request->server->get('CONTENT_LENGTH');
  81. }
  82. return isset($_SERVER['CONTENT_LENGTH'])
  83. ? (int) $_SERVER['CONTENT_LENGTH']
  84. : null;
  85. }
  86. }