# UploadedFile

class UploadedFile extends File

A file uploaded through a form.

## Methods

`public` | `` | `__construct(string $path, string $originalName, string $mimeType = null, int $error = null, bool $test = false)` | Accepts the information of the uploaded file as provided by the PHP global $_FILES. |
`public` | `string|null` | `guessExtension()` | Returns the extension based on the mime type. | from File
`public` | `string|null` | `getMimeType()` | Returns the mime type of the file. | from File
`public` | `File` | `move(string $directory, string $name = null)` | Moves the file to a new location. |
`protected` | `` | `getTargetFile($directory, $name = null)` | No description | from File
`protected` | `string` | `getName(string $name)` | Returns locale independent base name of the given path. | from File
`public` | `string|null` | `getClientOriginalName()` | Returns the original file name. |
`public` | `string` | `getClientOriginalExtension()` | Returns the original file extension. |
`public` | `string|null` | `getClientMimeType()` | Returns the file mime type. |
`public` | `string|null` | `guessClientExtension()` | Returns the extension based on the client mime type. |
`public` | `int|null` | `getClientSize()` | Returns the file size. |
`public` | `int` | `getError()` | Returns the upload error. |
`public` | `bool` | `isValid()` | Returns whether the file was uploaded successfully. |
`public static` | `int` | `getMaxFilesize()` | Returns the maximum size of an uploaded file as configured in php.ini. |
`public` | `string` | `getErrorMessage()` | Returns an informative upload error message. |

## Details

at line 63

### `__construct()`

`public __construct(string $path, string $originalName, string $mimeType = null, int $error = null, bool $test = false)`

Accepts the information of the uploaded file as provided by the PHP global $_FILES.

The file object is only created when the uploaded file is valid (i.e. when the isValid() method returns true). Otherwise the only methods that could be called on an UploadedFile instance are:

- getClientOriginalName,
- getClientMimeType,
- isValid,
- getError.

Calling any other method on an non-valid instance will cause an unpredictable result.

#### Parameters

`string` | `$path` | The path to the file
`string` | `$originalName` | The original file name of the uploaded file
`string` | `$mimeType` | The type of the file as provided by PHP; null defaults to application/octet-stream
`int` | `$error` | The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
`bool` | `$test` | Whether the test mode is active Local files are used in test mode hence the code should not enforce HTTP uploads

#### Exceptions

FileException | If file_uploads is disabled
FileNotFoundException | If the file does not exist

in File at line 56

### `guessExtension()`

`public string|null guessExtension()`

Returns the extension based on the mime type.

If the mime type is unknown, returns null.

This method uses the mime type as guessed by getMimeType() to guess the file extension.

#### Return Value

`string|null` | The guessed extension or null if it cannot be guessed

#### See also

ExtensionGuesser |
getMimeType() |

in File at line 75

### `getMimeType()`

`public string|null getMimeType()`

Returns the mime type of the file.

The mime type is guessed using a MimeTypeGuesser instance, which uses finfo(), mime_content_type() and the system binary "file" (in this order), depending on which of those are available.

#### Return Value

`string|null` | The guessed mime type (e.g. "application/pdf")

#### See also

MimeTypeGuesser |

at line 201

### `move()`

`public File move(string $directory, string $name = null)`

Moves the file to a new location.

#### Parameters

`string` | `$directory` | The destination folder
`string` | `$name` | The new file name

#### Return Value

`File` | A File object representing the new file

#### Exceptions

FileException | if, for any reason, the file could not have been moved

in File at line 106

### `getTargetFile()`

`protected getTargetFile($directory, $name = null)`

#### Parameters

| `$directory` |
| `$name` |

in File at line 128

### `getName()`

`protected string getName(string $name)`

Returns locale independent base name of the given path.

#### Parameters

`string` | `$name` | The new file name

#### Return Value

`string` | containing

at line 88

### `getClientOriginalName()`

`public string|null getClientOriginalName()`

Returns the original file name.

It is extracted from the request from which the file has been uploaded. Then it should not be considered as a safe value.

#### Return Value

`string|null` | The original name

at line 101

### `getClientOriginalExtension()`

`public string getClientOriginalExtension()`

Returns the original file extension.

It is extracted from the original file name that was uploaded. Then it should not be considered as a safe value.

#### Return Value

`string` | The extension

at line 119

### `getClientMimeType()`

`public string|null getClientMimeType()`

Returns the file mime type.

The client mime type is extracted from the request from which the file was uploaded, so it should not be considered as a safe value.

For a trusted mime type, use getMimeType() instead (which guesses the mime type based on the file content).

#### Return Value

`string|null` | The mime type

#### See also

getMimeType() |

at line 141

### `guessClientExtension()`

`public string|null guessClientExtension()`

Returns the extension based on the client mime type.

If the mime type is unknown, returns null.

This method uses the mime type as guessed by getClientMimeType() to guess the file extension. As such, the extension returned by this method cannot be trusted.

For a trusted extension, use guessExtension() instead (which guesses the extension based on the guessed mime type for the file).

#### Return Value

`string|null` | The guessed extension or null if it cannot be guessed

#### See also

guessExtension() |
getClientMimeType() |

at line 159

### `getClientSize()`

`public int|null getClientSize()`

Returns the file size.

It is extracted from the request from which the file has been uploaded. Then it should not be considered as a safe value.

#### Return Value

`int|null` | The file sizes

at line 174

### `getError()`

`public int getError()`

Returns the upload error.

If the upload was successful, the constant UPLOAD_ERR_OK is returned. Otherwise one of the other UPLOAD_ERR_XXX constants is returned.

#### Return Value

`int` | The upload error

at line 184

### `isValid()`

`public bool isValid()`

Returns whether the file was uploaded successfully.

#### Return Value

`bool` | True if the file has been uploaded with HTTP and no error occurred

at line 245

### `getMaxFilesize()`

`public static int getMaxFilesize()`

Returns the maximum size of an uploaded file as configured in php.ini.

#### Return Value

`int` | The maximum size of an uploaded file in bytes

at line 280

### `getErrorMessage()`

`public string getErrorMessage()`

Returns an informative upload error message.

#### Return Value

`string` | The error message regarding the specified error code

## Source code

    <?php

    /*
     * This file is part of the Symfony package.
     *
     * (c) Fabien Potencier <fabien@symfony.com>
     *
     * For the full copyright and license information, please view the LICENSE
     * file that was distributed with this source code.
     */

    namespace App\Khan\Component\HttpFoundation\File;

    use App\Khan\Component\HttpFoundation\File\Exception\CannotWriteFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\ExtensionFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\FileException;
    use App\Khan\Component\HttpFoundation\File\Exception\FileNotFoundException;
    use App\Khan\Component\HttpFoundation\File\Exception\FormSizeFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\IniSizeFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\NoFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\NoTmpDirFileException;
    use App\Khan\Component\HttpFoundation\File\Exception\PartialFileException;
    use App\Khan\Component\HttpFoundation\File\MimeType\ExtensionGuesser;

    /**
     * A file uploaded through a form.
     *
     * @author Bernhard Schussek <bschussek@gmail.com>
     * @author Florian Eckerstorfer <florian@eckerstorfer.org>
     * @author Fabien Potencier <fabien@symfony.com>
     */
    class UploadedFile extends File
    {
        private $test = false;
        private $originalName;
        private $mimeType;
        private $error;

        /**
         * Accepts the information of the uploaded file as provided by the PHP global $_FILES.
         *
         * The file object is only created when the uploaded file is valid (i.e. when the
         * isValid() method returns true). Otherwise the only methods that could be called
         * on an UploadedFile instance are:
         *
         *   * getClientOriginalName,
         *   * getClientMimeType,
         *   * isValid,
         *   * getError.
         *
         * Calling any other method on an non-valid instance will cause an unpredictable result.
         *
         * @param string      $path         The full temporary path to the file
         * @param string      $originalName The original file name of the uploaded file
         * @param string|null $mimeType     The type of the file as provided by PHP; null defaults to application/octet-stream
         * @param int|null    $error        The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
         * @param bool        $test         Whether the test mode is active
         *                                  Local files are used in test mode hence the code should not enforce HTTP uploads
         *
         * @throws FileException         If file_uploads is disabled
         * @throws FileNotFoundException If the file does not exist
         */
        public function __construct(string $path, string $originalName, string $mimeType = null, int $error = null, $test = false)
        {
            $this->originalName = $this->getName($originalName);
            $this->mimeType = $mimeType ?: 'application/octet-stream';

            if (4 < func_num_args() ? !is_bool($test) : null !== $error && @filesize($path) === $error) {
                @trigger_error(sprintf('Passing a size as 4th argument to the constructor of "%s" is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED);
                $error = $test;
                $test = 5 < func_num_args() ? func_get_arg(5) : false;
            }

            $this->error = $error ?: UPLOAD_ERR_OK;
            $this->test = $test;

            parent::__construct($path, UPLOAD_ERR_OK === $this->error);
        }

        /**
         * Returns the original file name.
         *
         * It is extracted from the request from which the file has been uploaded.
         * Then it should not be considered as a safe value.
         *
         * @return string|null The original name
         */
        public function getClientOriginalName()
        {
            return $this->originalName;
        }

        /**
         * Returns the original file extension.
         *
         * It is extracted from the original file name that was uploaded.
         * Then it should not be considered as a safe value.
         *
         * @return string The extension
         */
        public function getClientOriginalExtension()
        {
            return pathinfo($this->originalName, PATHINFO_EXTENSION);
        }

        /**
         * Returns the file mime type.
         *
         * The client mime type is extracted from the request from which the file
         * was uploaded, so it should not be considered as a safe value.
         *
         * For a trusted mime type, use getMimeType() instead (which guesses the mime
         * type based on the file content).
         *
         * @return string|null The mime type
         *
         * @see getMimeType()
         */
        public function getClientMimeType()
        {
            return $this->mimeType;
        }

        /**
         * Returns the extension based on the client mime type.
         *
         * If the mime type is unknown, returns null.
         *
         * This method uses the mime type as guessed by getClientMimeType()
         * to guess the file extension. As such, the extension returned
         * by this method cannot be trusted.
         *
         * For a trusted extension, use guessExtension() instead (which guesses
         * the extension based on the guessed mime type for the file).
         *
         * @return string|null The guessed extension or null if it cannot be guessed
         *
         * @see guessExtension()
         * @see getClientMimeType()
         */
        public function guessClientExtension()
        {
            $type = $this->getClientMimeType();
            $guesser = ExtensionGuesser::getInstance();

            return $guesser->guess($type);
        }

        /**
         * Returns the file size.
         *
         * It is extracted from the request from which the file has been uploaded.
         * Then it should not be considered as a safe value.
         *
         * @deprecated since Symfony 4.1, use getSize() instead.
         *
         * @return int|null The file sizes
         */
        public function getClientSize()
        {
            @trigger_error(sprintf('"%s" is deprecated since Symfony 4.1. Use getSize() instead.', __METHOD__), E_USER_DEPRECATED);

            return $this->getSize();
        }

        /**
         * Returns the upload error.
         *
         * If the upload was successful, the constant UPLOAD_ERR_OK is returned.
         * Otherwise one of the other UPLOAD_ERR_XXX constants is returned.
         *
         * @return int The upload error
         */
        public function getError()
        {
            return $this->error;
        }

        /**
         * Returns whether the file was uploaded successfully.
         *
         * @return bool True if the file has been uploaded with HTTP and no error occurred
         */
        public function isValid()
        {
            $isOk = UPLOAD_ERR_OK === $this->error;

            return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
        }

        /**
         * Moves the file to a new location.
         *
         * @param string $directory The destination folder
         * @param string $name      The new file name
         *
         * @return File A File object representing the new file
         *
         * @throws FileException if, for any reason, the file could not have been moved
         */
        public function move($directory, $name = null)
        {
            if ($this->isValid()) {
                if ($this->test) {
                    return parent::move($directory, $name);
                }

                $target = $this->getTargetFile($directory, $name);

                if (!@move_uploaded_file($this->getPathname(), $target)) {
                    $error = error_get_last();
                    throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
                }

                @chmod($target, 0666 & ~umask());

                return $target;
            }

            switch ($this->error) {
                case UPLOAD_ERR_INI_SIZE:
                    throw new IniSizeFileException($this->getErrorMessage());
                case UPLOAD_ERR_FORM_SIZE:
                    throw new FormSizeFileException($this->getErrorMessage());
                case UPLOAD_ERR_PARTIAL:
                    throw new PartialFileException($this->getErrorMessage());
                case UPLOAD_ERR_NO_FILE:
                    throw new NoFileException($this->getErrorMessage());
                case UPLOAD_ERR_CANT_WRITE:
                    throw new CannotWriteFileException($this->getErrorMessage());
                case UPLOAD_ERR_NO_TMP_DIR:
                    throw new NoTmpDirFileException($this->getErrorMessage());
                case UPLOAD_ERR_EXTENSION:
                    throw new ExtensionFileException($this->getErrorMessage());
            }

            throw new FileException($this->getErrorMessage());
        }

        /**
         * Returns the maximum size of an uploaded file as configured in php.ini.
         *
         * @return int The maximum size of an uploaded file in bytes
         */
        public static function getMaxFilesize()
        {
            $iniMax = strtolower(ini_get('upload_max_filesize'));

            if ('' === $iniMax) {
                return PHP_INT_MAX;
            }

            $max = ltrim($iniMax, '+');
            if (0 === strpos($max, '0x')) {
                $max = intval($max, 16);
            } elseif (0 === strpos($max, '0')) {
                $max = intval($max, 8);
            } else {
                $max = (int) $max;
            }

            switch (substr($iniMax, -1)) {
                case 't': $max *= 1024;
                // no break
                case 'g': $max *= 1024;
                // no break
                case 'm': $max *= 1024;
                // no break
                case 'k': $max *= 1024;
            }

            return $max;
        }

        /**
         * Returns an informative upload error message.
         *
         * @return string The error message regarding the specified error code
         */
        public function getErrorMessage()
        {
            static $errors = array(
                UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).',
                UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
                UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
                UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
                UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
                UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
                UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
            );

            $errorCode = $this->error;
            $maxFilesize = UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0;
            $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.';

            return sprintf($message, $this->getClientOriginalName(), $maxFilesize);
        }
    }