Tutorials

Native PHP: Tame Social Links with Identity Resolver for Community Directories

Native PHP: Tame Social Links with Identity Resolver for Community Directories

A community directory can turn a simple social-link field into a persistent maintenance problem. One member pastes a Facebook profile URL, another submits an Instagram link copied from a phone, and a third supplies a LinkedIn address with tracking parameters. Saving those strings is easy. Giving the application a consistent identity representation takes more care.

Identity Resolver provides that normalization boundary for public Facebook, Instagram, and LinkedIn references. This tutorial builds a Native PHP 8.3+ directory submission endpoint that validates incoming links, calls the resolver, and saves its normalized response alongside the original submission.

The implementation deliberately separates normalization from verification. A normalized identity does not establish account ownership, authorize directory edits, or justify a “verified member” badge.

Get access before writing the integration

  1. Open the official Identity Resolver documentation.
  2. Review the service and plan page for current availability and conditions.
  3. Account registration information and login information share that supplied service entry point here; separate registration and login URLs are not specified. Neither registration nor login is required for the current public endpoint.
  4. Make the first request without an API key or account token. There is no service credential to copy or store for this flow.

The exact operation is GET https://ai.mihajlo.mk/api/identity-resolver/v1/resolve. Send platform with a supported username, id, identifier, profile, or url parameter. Our directory accepts links, so it consistently uses url.

curl --get --show-error --fail-with-body \
  --connect-timeout 1 --max-time 4 \
  'https://ai.mihajlo.mk/api/identity-resolver/v1/resolve' \
  --data-urlencode 'platform=linkedin' \
  --data-urlencode 'url=https://www.linkedin.com/in/example/'

Replace the example with a public reference you intend to inspect. This checks connectivity and exposes the actual response; it does not guarantee that the illustrative profile exists.

Keep the architecture small and the boundary explicit

Use PHP 8.3+, Composer, cURL, PDO SQLite, and the extensions required by PHPUnit 11.5. One authenticated HTTP request performs validation, resolution, and persistence. Synchronous execution suits a small directory, provided the hosting request budget accommodates two bounded attempts.

The supplied contract does not enumerate response properties. Consequently, the domain mapper preserves the returned JSON object without guessing fields such as a canonical URL or account ID. This produces usable normalized records while keeping undocumented schema assumptions out of the application.

community-directory/
  .env
  composer.json
  schema.sql
  src.php
  public/index.php
  tests/ResolverTest.php
  var/

Create composer.json:

{
  "require": {
    "php": ">=8.3",
    "ext-curl": "*",
    "ext-json": "*",
    "ext-pdo": "*",
    "ext-pdo_sqlite": "*"
  },
  "require-dev": {
    "phpunit/phpunit": "^11.5"
  },
  "autoload": {
    "files": ["src.php"]
  }
}

Store configuration in .env before building the feature. No Identity Resolver credential belongs here. The following token protects our directory write endpoint; it never travels to the resolver.

DIRECTORY_WRITE_TOKEN="YOUR_DIRECTORY_WRITE_TOKEN"
DIRECTORY_DB="var/directory.sqlite"

Generate a replacement using php -r 'echo bin2hex(random_bytes(32)), PHP_EOL;'. Keep the environment file outside the public document root, exclude it from version control, and restrict its permissions. This project reads a small INI-compatible configuration file; it does not require a dotenv package.

Implement a bounded HTTP client and domain mapper

Put the following in src.php. The transport never follows redirects, limits response size, verifies TLS, and imposes separate connection and total timeouts.

<?php
declare(strict_types=1);

final readonly class WireResponse
{
    public function __construct(
        public int $status,
        public string $body,
    ) {}
}

final class DirectoryFailure extends RuntimeException
{
    public function __construct(
        public readonly string $reason,
        public readonly int $httpStatus,
    ) {
        parent::__construct($reason);
    }
}

final class TransportFailure extends RuntimeException {}

final class CurlTransport
{
    public function __invoke(string $url): WireResponse
    {
        $handle = curl_init($url);
        if ($handle === false) {
            throw new TransportFailure('curl_init');
        }

        $body = '';
        curl_setopt_array($handle, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_CONNECTTIMEOUT_MS => 700,
            CURLOPT_TIMEOUT_MS => 2500,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => ['Accept: application/json'],
            CURLOPT_WRITEFUNCTION => static function (
                $handle,
                string $chunk
            ) use (&$body): int {
                if (strlen($body) + strlen($chunk) > 65536) {
                    return 0;
                }
                $body .= $chunk;
                return strlen($chunk);
            },
        ]);

        try {
            if (curl_exec($handle) === false) {
                throw new TransportFailure('transport', curl_errno($handle));
            }
            return new WireResponse(
                (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE),
                $body,
            );
        } finally {
            curl_close($handle);
        }
    }
}

final readonly class DirectoryIdentity
{
    public function __construct(
        public string $platform,
        public string $submittedUrl,
        public stdClass $identity,
    ) {}
}

final class Resolver
{
    public function __construct(
        private Closure $send,
        private Closure $pause,
    ) {}

    public function resolve(string $platform, string $url): DirectoryIdentity
    {
        $hosts = [
            'facebook' => ['facebook.com', 'www.facebook.com', 'm.facebook.com'],
            'instagram' => ['instagram.com', 'www.instagram.com'],
            'linkedin' => ['linkedin.com', 'www.linkedin.com'],
        ];
        $parts = parse_url($url);
        if (
            !isset($hosts[$platform]) ||
            strlen($url) > 2048 ||
            filter_var($url, FILTER_VALIDATE_URL) === false ||
            $parts === false ||
            strtolower($parts['scheme'] ?? '') !== 'https' ||
            !in_array(strtolower($parts['host'] ?? ''), $hosts[$platform], true) ||
            isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])
        ) {
            throw new DirectoryFailure('invalid_link', 422);
        }

        $endpoint = 'https://ai.mihajlo.mk/api/identity-resolver/v1/resolve?';
        $requestUrl = $endpoint . http_build_query(
            ['platform' => $platform, 'url' => $url],
            '',
            '&',
            PHP_QUERY_RFC3986,
        );

        for ($attempt = 0; $attempt < 2; $attempt++) {
            try {
                $response = ($this->send)($requestUrl);
            } catch (TransportFailure $error) {
                $transient = in_array($error->getCode(), [6, 7, 28, 52, 56], true);
                if ($transient && $attempt === 0) {
                    ($this->pause)(random_int(100000, 200000));
                    continue;
                }
                throw new DirectoryFailure('upstream_transport', 502);
            }

            if (in_array($response->status, [429, 503], true)) {
                throw new DirectoryFailure('upstream_busy', 503);
            }
            if (
                $attempt === 0 &&
                in_array($response->status, [502, 504], true)
            ) {
                ($this->pause)(random_int(100000, 200000));
                continue;
            }
            if (in_array($response->status, [400, 422], true)) {
                throw new DirectoryFailure('reference_rejected', 422);
            }
            if ($response->status < 200 || $response->status >= 300) {
                throw new DirectoryFailure('upstream_http', 502);
            }

            try {
                $identity = json_decode(
                    $response->body, false, 64, JSON_THROW_ON_ERROR
                );
            } catch (JsonException) {
                throw new DirectoryFailure('upstream_schema', 502);
            }
            if (!$identity instanceof stdClass || get_object_vars($identity) === []) {
                throw new DirectoryFailure('upstream_schema', 502);
            }

            return new DirectoryIdentity($platform, $url, $identity);
        }

        throw new LogicException('Unreachable retry state');
    }
}

The host allowlist is intentionally a directory input policy, not a claim about every reference format the service supports. Localized or shortened links require an explicit policy change. Crucially, cURL connects only to the fixed resolver endpoint; it never fetches the submitted link directly.

Retries cover selected connection failures and HTTP 502/504, with jitter and one retry maximum. HTTP 429 and 503 immediately become deferred failures. This avoids sleeping inside a web worker or retrying through a server-requested delay. Authentication failures, rejected references, malformed JSON, and oversized responses receive no automatic retry.

Persist successful resolutions through one route

Create schema.sql. The key makes repeated submissions of the same source update one record. Different links may still identify the same account; do not invent a deduplication key from undocumented response properties.

CREATE TABLE directory_links (
    platform TEXT NOT NULL,
    source_url TEXT NOT NULL,
    identity_json TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    PRIMARY KEY (platform, source_url)
);

Create public/index.php. Its response fields are our application contract, distinct from Identity Resolver’s response.

<?php
declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';

$started = hrtime(true);
$status = 500;
$output = ['error' => 'internal_error'];

try {
    $config = parse_ini_file(
        dirname(__DIR__) . '/.env', false, INI_SCANNER_RAW
    );
    $token = $config['DIRECTORY_WRITE_TOKEN'] ?? '';
    if (strlen($token) < 32 || $token === 'YOUR_DIRECTORY_WRITE_TOKEN') {
        throw new RuntimeException('Configure the directory credential');
    }

    if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) !== '/submissions') {
        throw new DirectoryFailure('not_found', 404);
    }
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        header('Allow: POST');
        throw new DirectoryFailure('method_not_allowed', 405);
    }
    if (!hash_equals(
        'Bearer ' . $token,
        $_SERVER['HTTP_AUTHORIZATION'] ?? ''
    )) {
        throw new DirectoryFailure('unauthorized', 401);
    }

    $raw = file_get_contents('php://input', false, null, 0, 4097);
    if ($raw === false || strlen($raw) > 4096) {
        throw new DirectoryFailure('body_too_large', 413);
    }
    try {
        $input = json_decode($raw, true, 16, JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        throw new DirectoryFailure('invalid_json', 400);
    }
    if (
        !is_array($input) ||
        !is_string($input['platform'] ?? null) ||
        !is_string($input['url'] ?? null)
    ) {
        throw new DirectoryFailure('invalid_input', 422);
    }

    $resolver = new Resolver(
        Closure::fromCallable(new CurlTransport()),
        static fn (int $microseconds) => usleep($microseconds),
    );
    $record = $resolver->resolve($input['platform'], $input['url']);
    $identityJson = json_encode($record->identity, JSON_THROW_ON_ERROR);

    $db = new PDO(
        'sqlite:' . dirname(__DIR__) . '/' . $config['DIRECTORY_DB'],
        null,
        null,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 2],
    );
    $statement = $db->prepare(
        'INSERT INTO directory_links VALUES (?, ?, ?, CURRENT_TIMESTAMP)
         ON CONFLICT(platform, source_url) DO UPDATE SET
         identity_json = excluded.identity_json,
         updated_at = excluded.updated_at'
    );
    $statement->execute([
        $record->platform, $record->submittedUrl, $identityJson,
    ]);

    $status = 200;
    $output = [
        'platform' => $record->platform,
        'submitted_url' => $record->submittedUrl,
        'identity' => $record->identity,
    ];
} catch (DirectoryFailure $error) {
    $status = $error->httpStatus;
    $output = ['error' => $error->reason];
} catch (Throwable) {
    $status = 500;
    $output = ['error' => 'internal_error'];
}

error_log(json_encode([
    'event' => 'directory_submission',
    'status' => $status,
    'failure' => $output['error'] ?? null,
    'duration_ms' => round((hrtime(true) - $started) / 1000000),
], JSON_THROW_ON_ERROR));

http_response_code($status);
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode($output, JSON_THROW_ON_ERROR);

Normalization finishes before SQLite opens, so network delays hold no database lock. A failed refresh preserves the existing record. The shared bearer credential suits trusted server-side directory tooling; never embed it in browser JavaScript. A public member form needs its own session authorization, CSRF protection, and abuse controls before invoking this boundary.

Test failure paths without contacting the service

Create tests/ResolverTest.php. The synthetic fixture property below belongs only to the fake response; it asserts nothing about the service schema.

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

require_once dirname(__DIR__) . '/vendor/autoload.php';

final class ResolverTest extends TestCase
{
    public function testTransientFailureRetriesAndMaps(): void
    {
        $calls = 0;
        $pauses = 0;
        $resolver = new Resolver(
            static function (string $url) use (&$calls): WireResponse {
                parse_str((string) parse_url($url, PHP_URL_QUERY), $query);
                self::assertSame('instagram', $query['platform']);
                return ++$calls === 1
                    ? new WireResponse(502, '')
                    : new WireResponse(200, '{"fixture":true}');
            },
            static function (int $delay) use (&$pauses): void {
                self::assertGreaterThanOrEqual(100000, $delay);
                self::assertLessThanOrEqual(200000, $delay);
                $pauses++;
            },
        );
        $record = $resolver->resolve(
            'instagram', 'https://www.instagram.com/example/'
        );
        self::assertTrue($record->identity->fixture);
        self::assertSame(2, $calls);
        self::assertSame(1, $pauses);
    }

    public function testRateLimitDoesNotRetry(): void
    {
        $calls = 0;
        $resolver = new Resolver(
            static function () use (&$calls): WireResponse {
                $calls++;
                return new WireResponse(429, '');
            },
            static function (): void { self::fail('Unexpected retry'); },
        );
        try {
            $resolver->resolve('facebook', 'https://facebook.com/example');
            self::fail('Expected failure');
        } catch (DirectoryFailure $error) {
            self::assertSame('upstream_busy', $error->reason);
            self::assertSame(503, $error->httpStatus);
            self::assertSame(1, $calls);
        }
    }

    public function testMalformedResponseFailsClosed(): void
    {
        $resolver = new Resolver(
            static fn () => new WireResponse(200, 'not-json'),
            static function (): void { self::fail('Unexpected retry'); },
        );
        $this->expectExceptionMessage('upstream_schema');
        $resolver->resolve('linkedin', 'https://linkedin.com/in/example');
    }

    public function testLookalikeHostNeverReachesTransport(): void
    {
        $resolver = new Resolver(
            static function (): void { self::fail('Unexpected request'); },
            static function (): void { self::fail('Unexpected retry'); },
        );
        $this->expectExceptionMessage('invalid_link');
        $resolver->resolve(
            'linkedin', 'https://linkedin.com.attacker.test/in/example'
        );
    }
}

Run installation, initialize storage once, and execute the tests:

mkdir -p public tests var
composer install
php -r '$db = new PDO("sqlite:var/directory.sqlite"); $db->exec(file_get_contents("schema.sql"));'
vendor/bin/phpunit tests
php -S 127.0.0.1:8080 -t public public/index.php

From another terminal, submit a reference using the directory token configured earlier:

curl --show-error --fail-with-body \
  --max-time 10 \
  'http://127.0.0.1:8080/submissions' \
  -H 'Authorization: Bearer YOUR_DIRECTORY_WRITE_TOKEN' \
  -H 'Content-Type: application/json' \
  --data '{"platform":"instagram","url":"https://www.instagram.com/example/"}'

Deploy with deliberate operational limits

Use PHP-FPM behind an HTTPS web server for deployment; the built-in server is for local verification. Set the document root to public/, route /submissions to index.php, and ensure the web server forwards the Authorization header. Give the runtime access to its database directory, including permission to create SQLite journal files.

Keep the request budget above approximately 5.2 seconds of upstream work plus database and application overhead. Apply inbound concurrency and rate limits: a public resolver endpoint does not imply unlimited capacity. For repeated 429/503 failures, stop automatic submissions and investigate current service guidance before resuming.

Track failure counts and latency from the structured logs. Do not add submitted URLs, response bodies, or authorization headers to routine logs. TLS failures usually require checking the host’s CA configuration; disabling certificate verification is not a fix. A 502 with upstream_schema calls for checking the documented response contract, while local 500s warrant checking configuration, schema initialization, and storage permissions.

Verify the directory outcome

  • Run the automated tests successfully before deployment.
  • Submit one valid public link for each supported platform and inspect the saved normalized object.
  • Repeat an identical submission and confirm that its row updates.
  • Confirm malformed JSON, lookalike hosts, and incorrect directory credentials fail without saving records.
  • Confirm deferred upstream failures leave existing records intact.
  • Verify production HTTPS, header forwarding, database backups, and log access restrictions.

The useful result is a directory that owns its input rules and persistence while delegating public identity normalization to one explicit service boundary. Keep that boundary narrow, preserve what the contract actually guarantees, and social links become manageable records instead of permanent cleanup work.

Blog author portrait

Mihajlo

I’m Mihajlo — a developer driven by curiosity, discipline, and the constant urge to create something meaningful. I share insights, tutorials, and free services to help others simplify their work and grow in the ever-evolving world of software and AI.