Determining if a URL is a subdomain URL using PHP

I created a function to check whether a URL is a subdomain URL or not.

<?php

header("Content-Type: text/plain"); 

function checkSubDomain($url)
{

    $url = parse_url($url)["host"];

    if(strstr($url,'.',true)=='www')
    {
        return 0;
        break;
    }

    $domainExtensions = array(
                            '.com',
                            '.net',
                            '.org',
                            '.co.uk'
                            );

    foreach($domainExtensions as $extension)
    {
        if($extension == substr($url,-(strlen($extension))))
        {
            $url = substr($url,0,-(strlen($extension)));
        }

    }

    if (substr_count($url,'.') > 0)
    {
        return 1;
    }

}

//Sub-domain exists
if(checkSubDomain('http://SUBDOMAIN.example.com/page'))
{
    echo 'This URL contains a subdomain!';
    echo "\r\n";
}
else
{
    echo 'This URL does not have any subdomains!';
    echo "\r\n";
}

//No subdomain (www)    
if(checkSubDomain('http://www.example.com/page'))
{
    echo 'This URL contains a subdomain!';
    echo "\r\n";
}
else
{
    echo 'This URL does not have any subdomains!';
    echo "\r\n";
}

//Non-www URL (and no subdomain)
if(checkSubDomain('http://example.com/page'))
{
    echo 'This URL contains a subdomain!';
    echo "\r\n";
}
else
{
    echo 'This URL does not have any subdomains!';
    echo "\r\n";
}

Seems to be working perfectly (with the domain extensions needing updating), which leads me to ask...

  1. Is there a PHP command that can automatically store an array with all domain extensions or do I need to update it manually?

  2. AFTER removing all possible extensions from a given URL AND the domain doesn't start with www... Is it possible that it won't be a subdomain?

Answer №1

Have you ever considered breaking it down at the "."? By checking if the second-to-last part is ".co", you can determine if the extension has one or two parts. Similarly, examining the first part for "www" and counting the parts can indicate if it's a subdomain.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying outcomes from a pair of interlinked databases

I currently have two tables structured as: files id | path | filename changes id | file_id | change The file_id field is linked to the id in the files table. My use case for these tables involves storing information on which files have been changed a ...

Strange Glitch: The move_upload_file function fails to properly move files when the browser used is Internet Explorer versions 6, 7, or 9, and the hosting server is based on

I am facing a problem that has caught me off guard, and I could really use some help. (I am fairly new to Stackoverflow so please bear with me if I make any mistakes.) I am working on a simple 2-file application where the user selects a file on the index p ...

"Communicate through real-time chat applications by leveraging node.js, socket.io,

Looking to create a chat system using nodejs and socket.io, I have a working prototype but the question remains: how should I handle storing chat messages in the database? It doesn't seem practical to store every message as soon as a user presses ent ...

Break down a string into smaller segments within specific limitations using [PHP RegEx HTML] techniques

I have a task where I need to break down a long string into an array based on certain constraints: The input will be in HTML format, which could be a full page or just a portion of it. Each segment (new strings) should not exceed a specific number of cha ...

Python: The best method to divide a sentence into approximately equal sections

I've been attempting to develop a function that can divide a sentence into n lines, aiming for as even of distribution as possible. However, I'm encountering issues where either the first or last line ends up significantly longer than the rest. ...

The issue arises when trying to call a JavaScript function that has not been properly

Initially, write code in resources/js/app.js file function button1Clicked(){ console.log('Button 1 is clicked'); } Next, include the following code in testing.blade.php file <!DOCTYPE html> <html> <head> <meta name="cs ...

Creating an Identical Duplicate of a Returned Array in PHP: Mastering Array-Returning Functions

When working with PHP functions that return arrays, I noticed that when assigning the result to a variable like 'user' below, it creates a copy of the array and places it in index [0]. $user = query("SELECT * FROM `users` WHERE id = ?", $_SESSIO ...

Traversing a multi-dimensional array with changing keys in PHP

Recently delving back into the world of basic PHP, I encountered a roadblock while dealing with a JSON response. I successfully converted the response into an Array, but it seems to be multi-dimensional. The challenge lies in isolating and extracting value ...

"Check the position of the value in the if statement

Can you explain the distinction between these two statements: if (false === $variable) { //do something } and if ($variable === false) { //do something } I typically prefer the second format, but have noticed that many frameworks I work with use th ...

Creating an Effortless Update Form using Ajax and Utilizing both POST and GET Methods

As I delve into understanding jQuery's .ajax function, my ultimate goal is to enhance my site's CMS by updating content on the backend asynchronously. To kick things off, I'm crafting a basic form. I embed the id of the database via PHP in t ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

Changing the name of identical files in numerous folders to a different title

I have 3 folders named FOLDER1, FOLDER2, and FOLDER3. Each folder contains files such as file1.txt, file2.txt, file3.txt, and so on. There are no subfolders within these directories. Some files in these folders are duplicates, for example: FOLDER1 has fi ...

The SSL Client Certificate is Not Being Requested by Apache

Hello there! I must admit that configuring SSL is a new task for me. In the past, I've always relied on my IT department to handle it for me. So, please bear with me if I need some clarification on your answers. ...

Having trouble getting my WAMP localhost to work with Google Drive

I have searched countless times for a solution to my issue, but nothing seems to be working. My setup consists of WAMP 2.2 with Apache 2.4.2, and I am attempting to change the DocumentRoot to a different directory than the default one. http://localhost/p ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...

Utilizing AJAX to determine if a specific phrase includes the queried terms

Currently, I am working on an AJAX search bar. At the moment, it only allows me to search for exact words in my table. ID|Skillset|Description| 1|game|i love game 2|photography|i love to take photo 3|game|game is my forte My current query searches for ex ...

My server is experiencing issues with the functionality of the .htaccess file

My website can be accessed at https://itjmovies.com/milan/public/. I am trying to rewrite the URL using an .htaccess file. Specifically, I want to change it from https://itjmovies.com/milan/public/ to https://itjmovies.com/milan/, but my attempts have not ...

The recent upgrade to Laravel 5.2 has caused issues with PHPUnit, rendering it inoperable

To ensure our project stays current and can benefit from the latest developments, we made the upgrade from Laravel 5.1 to 5.2 yesterday. After spending some time tweaking our codebase, everything appears to be functioning normally, except for the fact that ...

Combine and update JSON files by matching ID's in PHP

I am facing an issue with merging JSON files in PHP. I want to overwrite data when the id's match, but it's not working as expected. Here is my PHP code: foreach($instagram_array['data'] as $key => $image){ $id = $image['id ...