vendor/symfony/http-foundation/File/UploadedFile.php line 32

Open in your IDE?
  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\HttpFoundation\File;
  11. use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException;
  12. use Symfony\Component\HttpFoundation\File\Exception\ExtensionFileException;
  13. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  14. use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
  15. use Symfony\Component\HttpFoundation\File\Exception\FormSizeFileException;
  16. use Symfony\Component\HttpFoundation\File\Exception\IniSizeFileException;
  17. use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
  18. use Symfony\Component\HttpFoundation\File\Exception\NoTmpDirFileException;
  19. use Symfony\Component\HttpFoundation\File\Exception\PartialFileException;
  20. use Symfony\Component\Mime\MimeTypes;
  21. /**
  22.  * A file uploaded through a form.
  23.  *
  24.  * @author Bernhard Schussek <bschussek@gmail.com>
  25.  * @author Florian Eckerstorfer <florian@eckerstorfer.org>
  26.  * @author Fabien Potencier <fabien@symfony.com>
  27.  */
  28. class UploadedFile extends File
  29. {
  30.     private $test;
  31.     private $originalName;
  32.     private $mimeType;
  33.     private $error;
  34.     /**
  35.      * Accepts the information of the uploaded file as provided by the PHP global $_FILES.
  36.      *
  37.      * The file object is only created when the uploaded file is valid (i.e. when the
  38.      * isValid() method returns true). Otherwise the only methods that could be called
  39.      * on an UploadedFile instance are:
  40.      *
  41.      *   * getClientOriginalName,
  42.      *   * getClientMimeType,
  43.      *   * isValid,
  44.      *   * getError.
  45.      *
  46.      * Calling any other method on an non-valid instance will cause an unpredictable result.
  47.      *
  48.      * @param string      $path         The full temporary path to the file
  49.      * @param string      $originalName The original file name of the uploaded file
  50.      * @param string|null $mimeType     The type of the file as provided by PHP; null defaults to application/octet-stream
  51.      * @param int|null    $error        The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
  52.      * @param bool        $test         Whether the test mode is active
  53.      *                                  Local files are used in test mode hence the code should not enforce HTTP uploads
  54.      *
  55.      * @throws FileException         If file_uploads is disabled
  56.      * @throws FileNotFoundException If the file does not exist
  57.      */
  58.     public function __construct(string $pathstring $originalNamestring $mimeType nullint $error nullbool $test false)
  59.     {
  60.         $this->originalName $this->getName($originalName);
  61.         $this->mimeType $mimeType ?: 'application/octet-stream';
  62.         $this->error $error ?: UPLOAD_ERR_OK;
  63.         $this->test $test;
  64.         parent::__construct($pathUPLOAD_ERR_OK === $this->error);
  65.     }
  66.     /**
  67.      * Returns the original file name.
  68.      *
  69.      * It is extracted from the request from which the file has been uploaded.
  70.      * Then it should not be considered as a safe value.
  71.      *
  72.      * @return string The original name
  73.      */
  74.     public function getClientOriginalName()
  75.     {
  76.         return $this->originalName;
  77.     }
  78.     /**
  79.      * Returns the original file extension.
  80.      *
  81.      * It is extracted from the original file name that was uploaded.
  82.      * Then it should not be considered as a safe value.
  83.      *
  84.      * @return string The extension
  85.      */
  86.     public function getClientOriginalExtension()
  87.     {
  88.         return pathinfo($this->originalNamePATHINFO_EXTENSION);
  89.     }
  90.     /**
  91.      * Returns the file mime type.
  92.      *
  93.      * The client mime type is extracted from the request from which the file
  94.      * was uploaded, so it should not be considered as a safe value.
  95.      *
  96.      * For a trusted mime type, use getMimeType() instead (which guesses the mime
  97.      * type based on the file content).
  98.      *
  99.      * @return string The mime type
  100.      *
  101.      * @see getMimeType()
  102.      */
  103.     public function getClientMimeType()
  104.     {
  105.         return $this->mimeType;
  106.     }
  107.     /**
  108.      * Returns the extension based on the client mime type.
  109.      *
  110.      * If the mime type is unknown, returns null.
  111.      *
  112.      * This method uses the mime type as guessed by getClientMimeType()
  113.      * to guess the file extension. As such, the extension returned
  114.      * by this method cannot be trusted.
  115.      *
  116.      * For a trusted extension, use guessExtension() instead (which guesses
  117.      * the extension based on the guessed mime type for the file).
  118.      *
  119.      * @return string|null The guessed extension or null if it cannot be guessed
  120.      *
  121.      * @see guessExtension()
  122.      * @see getClientMimeType()
  123.      */
  124.     public function guessClientExtension()
  125.     {
  126.         return MimeTypes::getDefault()->getExtensions($this->getClientMimeType())[0] ?? null;
  127.     }
  128.     /**
  129.      * Returns the upload error.
  130.      *
  131.      * If the upload was successful, the constant UPLOAD_ERR_OK is returned.
  132.      * Otherwise one of the other UPLOAD_ERR_XXX constants is returned.
  133.      *
  134.      * @return int The upload error
  135.      */
  136.     public function getError()
  137.     {
  138.         return $this->error;
  139.     }
  140.     /**
  141.      * Returns whether the file was uploaded successfully.
  142.      *
  143.      * @return bool True if the file has been uploaded with HTTP and no error occurred
  144.      */
  145.     public function isValid()
  146.     {
  147.         $isOk UPLOAD_ERR_OK === $this->error;
  148.         return $this->test $isOk $isOk && is_uploaded_file($this->getPathname());
  149.     }
  150.     /**
  151.      * Moves the file to a new location.
  152.      *
  153.      * @return File A File object representing the new file
  154.      *
  155.      * @throws FileException if, for any reason, the file could not have been moved
  156.      */
  157.     public function move(string $directorystring $name null)
  158.     {
  159.         if ($this->isValid()) {
  160.             if ($this->test) {
  161.                 return parent::move($directory$name);
  162.             }
  163.             $target $this->getTargetFile($directory$name);
  164.             set_error_handler(function ($type$msg) use (&$error) { $error $msg; });
  165.             $moved move_uploaded_file($this->getPathname(), $target);
  166.             restore_error_handler();
  167.             if (!$moved) {
  168.                 throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).'$this->getPathname(), $targetstrip_tags($error)));
  169.             }
  170.             @chmod($target0666 & ~umask());
  171.             return $target;
  172.         }
  173.         switch ($this->error) {
  174.             case UPLOAD_ERR_INI_SIZE:
  175.                 throw new IniSizeFileException($this->getErrorMessage());
  176.             case UPLOAD_ERR_FORM_SIZE:
  177.                 throw new FormSizeFileException($this->getErrorMessage());
  178.             case UPLOAD_ERR_PARTIAL:
  179.                 throw new PartialFileException($this->getErrorMessage());
  180.             case UPLOAD_ERR_NO_FILE:
  181.                 throw new NoFileException($this->getErrorMessage());
  182.             case UPLOAD_ERR_CANT_WRITE:
  183.                 throw new CannotWriteFileException($this->getErrorMessage());
  184.             case UPLOAD_ERR_NO_TMP_DIR:
  185.                 throw new NoTmpDirFileException($this->getErrorMessage());
  186.             case UPLOAD_ERR_EXTENSION:
  187.                 throw new ExtensionFileException($this->getErrorMessage());
  188.         }
  189.         throw new FileException($this->getErrorMessage());
  190.     }
  191.     /**
  192.      * Returns the maximum size of an uploaded file as configured in php.ini.
  193.      *
  194.      * @return int The maximum size of an uploaded file in bytes
  195.      */
  196.     public static function getMaxFilesize()
  197.     {
  198.         $sizePostMax self::parseFilesize(ini_get('post_max_size'));
  199.         $sizeUploadMax self::parseFilesize(ini_get('upload_max_filesize'));
  200.         return min($sizePostMax ?: PHP_INT_MAX$sizeUploadMax ?: PHP_INT_MAX);
  201.     }
  202.     /**
  203.      * Returns the given size from an ini value in bytes.
  204.      */
  205.     private static function parseFilesize($size): int
  206.     {
  207.         if ('' === $size) {
  208.             return 0;
  209.         }
  210.         $size strtolower($size);
  211.         $max ltrim($size'+');
  212.         if (=== strpos($max'0x')) {
  213.             $max = \intval($max16);
  214.         } elseif (=== strpos($max'0')) {
  215.             $max = \intval($max8);
  216.         } else {
  217.             $max = (int) $max;
  218.         }
  219.         switch (substr($size, -1)) {
  220.             case 't'$max *= 1024;
  221.             // no break
  222.             case 'g'$max *= 1024;
  223.             // no break
  224.             case 'm'$max *= 1024;
  225.             // no break
  226.             case 'k'$max *= 1024;
  227.         }
  228.         return $max;
  229.     }
  230.     /**
  231.      * Returns an informative upload error message.
  232.      *
  233.      * @return string The error message regarding the specified error code
  234.      */
  235.     public function getErrorMessage()
  236.     {
  237.         static $errors = [
  238.             UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).',
  239.             UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
  240.             UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
  241.             UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
  242.             UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
  243.             UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
  244.             UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
  245.         ];
  246.         $errorCode $this->error;
  247.         $maxFilesize UPLOAD_ERR_INI_SIZE === $errorCode self::getMaxFilesize() / 1024 0;
  248.         $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.';
  249.         return sprintf($message$this->getClientOriginalName(), $maxFilesize);
  250.     }
  251. }