PHP code example of craftcms / url-validator

1. Go to this page and download the library: Download craftcms/url-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

craftcms / url-validator example snippets


use CraftCms\UrlValidator\UrlValidationException;
use CraftCms\UrlValidator\UrlValidator;

$validator = new UrlValidator();
$url = 'https://example.com/image.jpg';

try {
    // Returns the validated IP addresses the host resolves to.
    $ips = $validator->validate($url);
} catch (UrlValidationException $e) {
    // The URL, or an IP it resolves to, is disallowed.
    echo $e->getMessage();
}

$parts = parse_url($url);
$host = $parts['host'];
$port = $parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80);

$client = new \GuzzleHttp\Client();
$response = $client->get($url, [
    'curl' => [
        // Pin the hostname/port to the IPs we just validated.
        CURLOPT_RESOLVE => ["$host:$port:" . implode(',', $ips)],
    ],
]);

$validator = new UrlValidator();

$validator->validateIp('8.8.8.8'); // true
$validator->validateIp('169.254.169.254'); // false (AWS metadata IP)
$validator->validateIp('10.0.0.5'); // false (private range)

$validator = new UrlValidator(fn(string $host): array => [
    // ...resolved IP addresses for $host
]);

// Allow private IP addresses but keep the reserved ranges disallowed
$validator = new UrlValidator(options: ['ipv4FilterFlags' => FILTER_FLAG_NO_RES_RANGE]);

$validator = new UrlValidator(options: [
    'allowedPrivateHosts' => [
        'my-api.internal',
        '*.ddev.site',
    ],
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RESOLVE, $validator->curlResolve($url));

GuzzleMiddleware::attach($client, $validator);

use CraftCms\UrlValidator\GuzzleMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
GuzzleMiddleware::push($stack, $validator);
$client = new Client(['handler' => $stack]);
bash
composer analyse