PHP Classes

File: src/DataTypes/UrlValidator.php

Recommend this page to a friend!
  Packages of Amirreza Ebrahimi   HeroQR Powerful PHP QR Code Library to generate PNG, SVG, PDF, Logos Ready to Use with Laravel   src/DataTypes/UrlValidator.php   Download  
File: src/DataTypes/UrlValidator.php
Role: Class source
Content type: text/plain
Description: Class source
Class: HeroQR Powerful PHP QR Code Library to generate PNG, SVG, PDF, Logos Ready to Use with Laravel
Generate QR code images in several formats
Author: By
Last change:
Date: 22 days ago
Size: 1,053 bytes
 

Contents

Class file image Download
<?php

namespace HeroQR\DataTypes;

use
HeroQR\Contracts\DataTypes\AbstractDataType;

/**
 * Validates URLs to ensure proper structure and prevent unsafe content.
 *
 * Checks:
 * - URL format (http/https)
 * - Valid domain (host)
 * - No SQL injections, script tags, or relative path traversals
 *
 * Example:
 * Url::validate("https://HeroQR.ir");
 */
class UrlValidator extends AbstractDataType
{
    public static function
validate(string $data): bool
   
{
       
$url = trim($data);
       
$parsedUrl = parse_url($url);

        if (!
filter_var($url, FILTER_VALIDATE_URL) || empty($parsedUrl['host'])) {
            return
false;
        }

        if (
            !
preg_match('/^(https?:\/\/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9-]+(?:\/[^\s]*)?(\?[^\s]*)?(#\S*)?)$/i', $url)
            && !
filter_var($url, FILTER_VALIDATE_IP)
        ) {
            return
false;
        }

        if (
self::hasSqlInjection($url) || self::hasScriptTag($url) || preg_match('/(\.\.\/)/', $url)) {
            return
false;
        }

        return
true;
    }
}