UrlHelper

Introduction

The UrlHelper class in JiFramework provides a set of utility methods for working with URLs in your application. It includes functions to retrieve information about the current page URL, host, referrer, and to parse and build URLs. These methods simplify common tasks related to URL manipulation, validation, and extraction of components.

By using the UrlHelper class, developers can efficiently handle URL operations without repeatedly writing boilerplate code, ensuring consistency and reducing the likelihood of errors.

Usage:

// Option 1: Initialize the HttpRequestHelper through the App
use JIFramework\Core\App\App;
$app = new App();
$url= $app->url;

OR 

// Option 2: Directly instantiate the HttpRequestHelper
use JIFramework\Core\Network\UrlHelper;
$url = new UrlHelper();

Explanation:

  • Option 1: Initializes the App class and retrieves the UrlHelper instance through it, using the framework's main entry point.
  • Option 2: Directly creates a UrlHelper instance.

getHostURL()

Method: getHostURL(): string

Description: Retrieves the host URL, which includes the protocol and host name, excluding the path and query string.

Parameters: None

Returns: A string representing the host URL.

Usage:

$hostUrl = $url->getHostURL();

echo $hostUrl;

// Example output:
// https://www.example.com

Explanation:

  • Determines the protocol by checking for HTTPS and forwarded protocols.
  • Constructs the host URL using the protocol and HTTP_HOST server variable.
  • Useful when you need the base URL of the site for constructing absolute URLs.

getReferrerUrl()

Method: getReferrerUrl(): ?string

Description: Retrieves the referring URL, i.e., the URL of the page that linked to the current page.

Parameters: None

Returns:

  • A string containing the referrer URL if available.
  • null if the referrer is not set.

Usage:

$referrerUrl = $url->getReferrerUrl();

if ($referrerUrl !== null) {
    echo 'Referrer: ' . $referrerUrl;
} else {
    echo 'No referrer available.';
}

// Example output if referrer is available:
// Referrer: https://www.google.com/search?q=example

// Example output if no referrer:
// No referrer available.

Explanation:

  • Checks if HTTP_REFERER is set in the server variables.
  • Returns the referrer URL or null if not available.
  • Useful for analytics, logging, or redirecting users back to the previous page.

getDomainInfo()

Method: getDomainInfo(string $url): array|false

Description: Extracts domain information from a given URL, including the domain name and its corresponding IP address.

Parameters:

  • $url (string): The URL from which to extract domain information.

Returns:

  • An associative array containing:
    • 'domain_name' (string): The domain name extracted from the URL.
    • 'domain_ip' (string): The IP address corresponding to the domain name.
  • false if the URL is invalid or the host component is missing.

Usage:

$url = 'https://www.example.com/path?param=value';

$domainInfo = $url->getDomainInfo($url);

if ($domainInfo !== false) {
    echo 'Domain Name: ' . $domainInfo['domain_name'] . PHP_EOL;
    echo 'Domain IP: ' . $domainInfo['domain_ip'];
} else {
    echo 'Invalid URL.';
}

// Example output:
// Domain Name: www.example.com
// Domain IP: 93.184.216.34

Explanation:

  • Parses the URL to extract the host component.
  • Uses gethostbyname() to resolve the domain name to an IP address.
  • Returns false if the URL is malformed or missing a host.
  • Useful for network diagnostics or logging domain information.

getQueryVariables()

Method: getQueryVariables(string $url): array

Description: Parses a URL and returns an associative array of query parameters.

Parameters:

  • $url (string): The URL from which to extract query variables.

Returns:

  • An associative array of query variables.
  • An empty array if the URL has no query string.

Usage:

$url = 'https://www.example.com/search?q=php+url+helper&page=2';

$queryVars = $url->getQueryVariables($url);

print_r($queryVars);

/* Example output:
Array
(
    [q] => php url helper
    [page] => 2
) */

Explanation:

  • Parses the URL to extract the query component.
  • Uses parse_str() to convert the query string into an associative array.
  • Useful for extracting parameters from URLs for processing or validation.

buildUrl()

Method: buildUrl(string $baseUrl, array $params = []): string

Description: Builds a full URL by appending query parameters to a base URL.

Parameters:

  • $baseUrl (string): The base URL to which query parameters will be appended.
  • $params (array, optional): An associative array of query parameters.

Returns: A string representing the full URL with query parameters.

Usage:

$baseUrl = 'https://www.example.com/search';
$params = [
    'q' => 'php url helper',
    'page' => 2,
];

$fullUrl = $url->buildUrl($baseUrl, $params);

echo $fullUrl;

// Example output:
// https://www.example.com/search?q=php+url+helper&page=2

Explanation:

  • Uses http_build_query() to create a query string from the parameters.
  • Determines whether to use '?' or '&' based on the presence of existing query parameters in the base URL.
  • Returns the constructed URL.
  • Useful for generating URLs for links, redirects, or API requests.

isValidUrl()

Method: isValidUrl(string $url): bool

Description: Validates whether a given string is a well-formed URL.

Parameters:

  • $url (string): The URL to validate.

Returns:

  • true if the URL is valid.
  • false if the URL is invalid.

Usage:

$url = 'https://www.example.com';

if ($url->isValidUrl($url)) {
    echo 'The URL is valid.';
} else {
    echo 'The URL is invalid.';
}

// Example output:
// The URL is valid.

Explanation:

  • Uses PHP's filter_var() function with FILTER_VALIDATE_URL to check validity.
  • Useful for input validation, ensuring that URLs provided by users are properly formatted.

parseUrlComponents()

Method: parseUrlComponents(string $url): array|false

Description: Parses a URL and returns its components as an associative array.

Parameters:

  • $url (string): The URL to parse.

Returns:

  • An associative array containing components of the URL (e.g., scheme, host, path, query).
  • false if the URL is malformed.

Usage:

$url = 'https://www.example.com:8080/path/to/page.php?param=value#section';

$urlComponents = $url->parseUrlComponents($url);

print_r($urlComponents);

// Example output:
// Array
// (
//     [scheme] => https
//     [host] => www.example.com
//     [port] => 8080
//     [path] => /path/to/page.php
//     [query] => param=value
//     [fragment] => section
// )

Explanation:

  • Uses parse_url() to break down the URL into its components.
  • Each component (if present) is included in the returned array.
  • Useful for analyzing or manipulating specific parts of a URL.