How to prevent the use of global variable $_FILES in code?
Magento application does not directly use any PHP superglobals variable like $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST.
You don’t need to directly use $_FILES in your code for file/images save. This may be lead to security vulnerabilities.
When you are using tools like GrumPHP, At your code commit time, You facing error like Use of $_FILES is discouraged in Magento 2.
Prevent of this error, You have to use an alternative way of $_FILES using Magento 2 with Magento\Framework\HTTP\PhpEnvironment\Request class.
You need to add Request.php class into the constructor as a dependency injection.
<?php
use Magento\Framework\HTTP\PhpEnvironment\Request;
class FilesAlternative
{
/**
* @var Request
*/
protected $request;
/**
* Validate constructor.
*
* @param Request $request
*/
public function __construct(
Request $request
) {
$this->request = $request;
}
public function saveImage() {
$files = $this->request->getFiles()->toArray(); // same as $_FIELS
if (isset($files['import_file']['name'])) {
//do your logic for save file
}
}
In above function, $this->request->getFiles()->toArray() gives output same as $_FILES.
