How to Check Server Outbound IP in ThinkPHP

Autor:Lisa Farrell·2026-06-01

In a ThinkPHP project, a server-side request to https://my.ipin.io/info checks the outbound IP used by the server when it accesses the public internet. This is for operations diagnostics, proxy checks, and cloud server region verification, not visitor personalization.

Design goal

For “How to Check Server Outbound IP in ThinkPHP”, the page must remain useful before the IP request finishes. The geo result is an enhancement: it is validated, applied to one narrow decision, and discarded when it is incomplete.

Request and decision flow

How to Check Server Outbound IP in ThinkPHP: The flow below is specific to this implementation rather than a generic IP lookup checklist.

  1. Step 1: Inject an endpoint into OutboundIpService so tests never depend on the public network. OutboundIpService(endpoint)
  2. Step 2: Request /info with cURL connect and total timeouts; do not enable automatic redirects. connect=1.2s; total=3s
  3. Step 3: Accept only HTTP 200 and a valid public IP; normalize country to two uppercase letters. ip + country validation
  4. Step 4: Cache the last successful result for five minutes and return it when the network fails. Cache::set(..., 300)
  5. Step 5: Log status, cURL error and duration without logging unrelated visitor data. Log::warning context

Production-oriented example

How to Check Server Outbound IP in ThinkPHP: This example adds a timeout, response validation, a deterministic fallback, and framework-specific lifecycle handling.

<?php
namespace app\service;

use think\facade\Cache;
use think\facade\Log;

final class OutboundIpService
{
    public function __construct(
        private string $endpoint = 'https://my.ipin.io/info'
    ) {}

    public function lookup(): array
    {
        $fallback = Cache::get('ipin:last_good', [
            'ip' => 'Unknown', 'country' => 'ZZ',
            'region' => '', 'city' => '', 'source' => 'fallback'
        ]);
        $started = microtime(true);
        $ch = curl_init($this->endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT_MS => 1200,
            CURLOPT_TIMEOUT_MS => 3000,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_HTTPHEADER => ['Accept: application/json'],
            CURLOPT_USERAGENT => 'ipin-outbound-check/1.0',
        ]);

        try {
            $body = curl_exec($ch);
            if ($body === false) {
                throw new \RuntimeException('cURL: '.curl_error($ch));
            }
            $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            if ($status !== 200) {
                throw new \RuntimeException('HTTP '.$status);
            }
            $data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
            $ip = filter_var($data['ip'] ?? '', FILTER_VALIDATE_IP,
                FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
            $country = strtoupper((string) ($data['country'] ?? ''));
            if (!$ip || !preg_match('/^[A-Z]{2}$/', $country)) {
                throw new \UnexpectedValueException('Invalid IP payload');
            }
            $result = [
                'ip' => $ip, 'country' => $country,
                'region' => (string) ($data['region'] ?? ''),
                'city' => (string) ($data['city'] ?? ''),
                'source' => 'live',
            ];
            Cache::set('ipin:last_good', $result, 300);
            return $result;
        } catch (\Throwable $e) {
            Log::warning('Outbound IP lookup failed', [
                'message' => $e->getMessage(),
                'duration_ms' => (int) ((microtime(true) - $started) * 1000),
            ]);
            return $fallback;
        } finally {
            curl_close($ch);
        }
    }
}

Test matrix

Run these cases against a mock response or a controlled VPN exit before publishing How to Check Server Outbound IP in ThinkPHP.

ConditionInput / setupExpected result
HTTP 200 JSONip=203.0.113.10, country=JPsource=live; cache updated
Proxy migrationoutbound IP changesnew IP appears after cache expiry
cURL timeouterror 28last_good or Unknown; warning log
Invalid payloadcountry missing / private IPpayload rejected; no cache overwrite

Automated / smoke test

public function test_rejects_incomplete_payload(): void
{
    $service = new OutboundIpService('http://127.0.0.1:9081/missing-country');
    $result = $service->lookup();
    $this->assertSame('fallback', $result['source']);
}

Failure handling

How to Check Server Outbound IP in ThinkPHP: An error must be visible in logs or developer tools, but it must not leave the visitor with an empty block or a broken checkout.

FailureCauseResponse
cURL error 6 / 60DNS or CA certificate failurekeep cached value; verify resolver and CA bundle
HTTP 429 / 5xxremote service unavailabledo not retry in the page request loop; use short cache
allow_url_fopen disabledfile_get_contents implementation breaksuse cURL as shown instead of changing php.ini
Unexpected proxy IPserver traffic uses a different egress routecompare proxy and container networking before editing allowlists

Practical application

A realistic use case for How to Check Server Outbound IP in ThinkPHP: after moving an API server behind a new proxy, operations compares the detected outbound IP with a vendor allowlist and records the last known good value.

Production notes

How to Check Server Outbound IP in ThinkPHP: Keep the default HTML complete, avoid treating IP location as identity, and do not use the client-side result as an authorization control.

Conclusion

How to Check Server Outbound IP in ThinkPHP now has its own implementation path, test evidence, and fallback behavior instead of sharing a generic article template.