0 follower

Class yii\web\MultipartFormDataParser

Inheritanceyii\web\MultipartFormDataParser » yii\base\BaseObject
Implementsyii\base\Configurable, yii\web\RequestParserInterface
Available since version2.0.10
Source Code https://github.com/yiisoft/yii2/blob/master/framework/web/MultipartFormDataParser.php

MultipartFormDataParser parses content encoded as 'multipart/form-data'.

This parser provides the fallback for the 'multipart/form-data' processing on non POST requests, for example: the one with 'PUT' request method.

In order to enable this parser you should configure yii\web\Request::$parsers in the following way:

return [
    'components' => [
        'request' => [
            'parsers' => [
                'multipart/form-data' => 'yii\web\MultipartFormDataParser'
            ],
        ],
        // ...
    ],
    // ...
];

Method parse() of this parser automatically populates $_FILES with the files parsed from raw body.

Note: since this is a request parser, it will initialize $_FILES values on yii\web\Request::getBodyParams(). Until this method is invoked, $_FILES array will remain empty even if there are submitted files in the request body. Make sure you have requested body params before any attempt to get uploaded file in case you are using this parser.

Usage example:

use yii\web\UploadedFile;

$restRequestData = Yii::$app->request->getBodyParams();
$uploadedFile = UploadedFile::getInstancesByName('photo');

$model = new Item();
$model->populate($restRequestData);
copy($uploadedFile->tempName, '/path/to/file/storage/photo.jpg');

Note: although this parser fully emulates regular structure of the $_FILES, related temporary files, which are available via tmp_name key, will not be recognized by PHP as uploaded ones. Thus functions like is_uploaded_file() and move_uploaded_file() will fail on them.

Public Properties

Hide inherited properties

Property Type Description Defined By
$force boolean Whether to parse raw body even for 'POST' request and $_FILES already populated. yii\web\MultipartFormDataParser
$uploadFileMaxCount integer Maximum upload files count. yii\web\MultipartFormDataParser
$uploadFileMaxSize integer Upload file max size in bytes. yii\web\MultipartFormDataParser

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
getUploadFileMaxCount() yii\web\MultipartFormDataParser
getUploadFileMaxSize() yii\web\MultipartFormDataParser
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
parse() Parses a HTTP request body. yii\web\MultipartFormDataParser
setUploadFileMaxCount() yii\web\MultipartFormDataParser
setUploadFileMaxSize() yii\web\MultipartFormDataParser

Property Details

Hide inherited properties

$force public property (available since version 2.0.13)

Whether to parse raw body even for 'POST' request and $_FILES already populated. By default this option is disabled saving performance for 'POST' requests, which are already processed by PHP automatically. > Note: if this option is enabled, value of $_FILES will be reset on each parse.

public boolean $force false
$uploadFileMaxCount public property

Maximum upload files count.

$uploadFileMaxSize public property

Upload file max size in bytes.

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
getUploadFileMaxCount() public method

public integer getUploadFileMaxCount ( )
return integer

Maximum upload files count.

                public function getUploadFileMaxCount()
{
    if ($this->_uploadFileMaxCount === null) {
        $this->_uploadFileMaxCount = (int)ini_get('max_file_uploads');
    }
    return $this->_uploadFileMaxCount;
}

            
getUploadFileMaxSize() public method

public integer getUploadFileMaxSize ( )
return integer

Upload file max size in bytes.

                public function getUploadFileMaxSize()
{
    if ($this->_uploadFileMaxSize === null) {
        $this->_uploadFileMaxSize = $this->getByteSize(ini_get('upload_max_filesize'));
    }
    return $this->_uploadFileMaxSize;
}

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Defined in: yii\base\BaseObject::init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
}

            
parse() public method

Parses a HTTP request body.

public array parse ( $rawBody, $contentType )
$rawBody string

The raw HTTP request body.

$contentType string

The content type specified for the request body.

return array

Parameters parsed from the request body

                public function parse($rawBody, $contentType)
{
    if (!$this->force) {
        if (!empty($_POST) || !empty($_FILES)) {
            // normal POST request is parsed by PHP automatically
            return $_POST;
        }
    } else {
        $_FILES = [];
    }
    if (empty($rawBody)) {
        return [];
    }
    if (!preg_match('/boundary="?(.*)"?$/is', $contentType, $matches)) {
        return [];
    }
    $boundary = trim($matches[1], '"');
    $bodyParts = preg_split('/\\R?-+' . preg_quote($boundary, '/') . '/s', $rawBody);
    array_pop($bodyParts); // last block always has no data, contains boundary ending like `--`
    $bodyParams = [];
    $filesCount = 0;
    foreach ($bodyParts as $bodyPart) {
        if (empty($bodyPart)) {
            continue;
        }
        list($headers, $value) = preg_split('/\\R\\R/', $bodyPart, 2);
        $headers = $this->parseHeaders($headers);
        if (!isset($headers['content-disposition']['name'])) {
            continue;
        }
        if (isset($headers['content-disposition']['filename'])) {
            // file upload:
            if ($filesCount >= $this->getUploadFileMaxCount()) {
                continue;
            }
            $fileInfo = [
                'name' => $headers['content-disposition']['filename'],
                'type' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'),
                'size' => StringHelper::byteLength($value),
                'error' => UPLOAD_ERR_OK,
                'tmp_name' => null,
            ];
            if ($fileInfo['size'] > $this->getUploadFileMaxSize()) {
                $fileInfo['error'] = UPLOAD_ERR_INI_SIZE;
            } else {
                $tmpResource = tmpfile();
                if ($tmpResource === false) {
                    $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
                } else {
                    $tmpResourceMetaData = stream_get_meta_data($tmpResource);
                    $tmpFileName = $tmpResourceMetaData['uri'];
                    if (empty($tmpFileName)) {
                        $fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
                        @fclose($tmpResource);
                    } else {
                        fwrite($tmpResource, $value);
                        rewind($tmpResource);
                        $fileInfo['tmp_name'] = $tmpFileName;
                        $fileInfo['tmp_resource'] = $tmpResource; // save file resource, otherwise it will be deleted
                    }
                }
            }
            $this->addFile($_FILES, $headers['content-disposition']['name'], $fileInfo);
            $filesCount++;
        } else {
            // regular parameter:
            $this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
        }
    }
    return $bodyParams;
}

            
setUploadFileMaxCount() public method

public void setUploadFileMaxCount ( $uploadFileMaxCount )
$uploadFileMaxCount integer

Maximum upload files count.

                public function setUploadFileMaxCount($uploadFileMaxCount)
{
    $this->_uploadFileMaxCount = $uploadFileMaxCount;
}

            
setUploadFileMaxSize() public method

public void setUploadFileMaxSize ( $uploadFileMaxSize )
$uploadFileMaxSize integer

Upload file max size in bytes.

                public function setUploadFileMaxSize($uploadFileMaxSize)
{
    $this->_uploadFileMaxSize = $uploadFileMaxSize;
}