Fiko Borizqy
Fiko Borizqy

Fiko Borizqy

Magento 2: How to Call Global Variable $_SERVER

Fiko Borizqy
·Jun 11, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Calling $_SERVER directly to that variable is not recommended, so how do we call that variable in Magento 2?

Magento 2 has class of \Magento\Framework\App\RequestInterface, and in order to call $_SERVER, we need to use this class. Implementing this class is pretty straight forward, just need to add this class to constructor, this is the example: (e.g. I'm calling $_SERVER['HTTP_REFERER'])

<?php

namespace Fiko\Training\Helper;

class Data
{
    public function __construct(
        \Magento\Framework\App\RequestInterface $httpRequest
    ) {
        $this->request = $httpRequest;
    }

    public function execute()
    {
        .....
        $httpReferer = $this->request->getServer('HTTP_REFERER');
        .....
    }
}

That's it, feel free to leave any comment.

 
Share this