user6838184
user6838184

Reputation:

get Client IP Symfony3

How to get client ip address in form builder symfony?

I have class CompanyType.php (AppBundle/Form/CompanyType.php)

$builder->add('ip', TextType::class, array(
    'label'=> 'IP Address',
    'data' => '127.0.0.1'
));  

I want to get the current client ip address that someone is using and put it on data parameters. How do I do that?

Upvotes: 0

Views: 6864

Answers (2)

gabrielrincon
gabrielrincon

Reputation: 896

The correct method in a controller is:

use Symfony\Component\HttpFoundation\Request;

....

public function myMethodAction(Request $request)
{
    $ip = $request->getClientIp();
    .....

}

Upvotes: 4

Tim
Tim

Reputation: 2187

I believe that this should work:

$ip = $this->request->getClientIp();
if($ip == 'unknown'){
    $ip = $_SERVER['REMOTE_ADDR'];
}

The getClientIp() function looks for the X-Forwarded-For header, which may not be set. If not then you can just get the IP address out of the $_SERVER variable like in any other PHP page.

http://api.symfony.com/master/Symfony/Component/HttpFoundation/Request.html#method_getClientIp

Upvotes: 2

Related Questions