Categories
Magento

How to remove error direct use of $_FILES Superglobal detected in magento2

In this tutorial, We’ll learn how to use magento method instead of php global variables.

Magento does not support direct use of Global variable in files e.g $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST

This practice is not supportable by coding standard and this can be cause of security issues. So when you check phpcs issues then you will see “direct use of $_FILES Superglobal detected” error.

You must use an alternative method of $_FILES when using Magento 2 to avoid this problem with Magento\Framework\HTTP\PhpEnvironment\Request or Magento\Framework\App\Request\Http class

1. 
<?php
namespace Vendor_Name\Module_Name\File_Path;

use Magento\Framework\HTTP\PhpEnvironment\Request;

class ImportFile
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * Validate constructor.
     *
     * @param Request $request
     */
    public function __construct(
        Request $request
    ) {
        $this->request = $request;
    }

    public function saveFile() {
        $files = $this->request->getFiles()->toArray(); // same as $_FIELS
        if (isset($files['import_file']['name'])) {
        	//do your logic for save file
        }
    }
2. 
<?php
namespace Vendor_Name\Module_Name\File_Path;

use Magento\Framework\App\Request\Http;

class ImportFile
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * Validate constructor.
     *
     * @param Request $request
     */
    public function __construct(
        Request $request
    ) {
        $this->request = $request;
    }

    public function saveFile() {
        $files = $this->request->getFiles(); // same as $_FIELS
        if (isset($files['import_file']['name'])) {
        	//do your logic for save file
        }
    }

These solution gives result same as $_FILES.
Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *