Getting your public IP address with the Symfony HTTP client

Published on 2020-07-05 • Modified on 2020-07-05

In this snippet, we will see how to get your public IP address with the Symfony HTTP client. Be careful that here, by public IP, I mean the public IP of the server running the PHP script not the IP of the browser accessing the website. Of course, this snippet is not specific to Symfony as you could do it with regular PHP/CURL. But it's so convenient with the HTTP client; it would be a pity not to use it.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property HttpClientInterface $httpClient
 */
trait Snippet99Trait
{
    public function snippet99(): void
    {
        try {
            echo $this->httpClient->request('GET', 'https://ipecho.net/plain')->getContent();
        } catch (\Exception) {
            echo 'An error occured when getting the public IP of the server.';
        }

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow  More on the web  Random snippet

  Work with me!