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);

// src/Controller/Snippet/Snippet99Trait.php

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 $e) {
            echo 'An error occured when getting the public IP of the server.';
        }

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow  More on the web  Random snippet

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use App\Utility\Ipstack;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet99Trait::snippet99
 * @covers Ipstack::getPublicIp
 */
final class Snippet99Test extends KernelTestCase
{
    private $httpClient;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->httpClient = self::$container->get('http_client');
    }

    /**
     * @covers Snippet99Trait::snippet99
     */
    public function testSnippet99(): void
    {
        $ip = $this->httpClient->request('GET', 'https://ipecho.net/plain')->getContent();
        self::assertNotEmpty(filter_var($ip, FILTER_VALIDATE_IP));
    }
}