How to get the Domain Name from URL in PHP
Table of Contents
PHP is a programming language almost exclusively used to create web applications.
A good reason for this is PHP's ease-of-use regarding anything to do with the web.
One of the things PHP makes easy is working with URLs and paths.
In this post, we'll learn how to extract the domain name from a URL using PHP.
How to get the domain name from a URL in PHP
Let's start out with an example URL:
PHP$url = "https://sabe.io/blog/php-domain-name-url";
To get the domain name from this, we must first parse the URL using PHP's built-in parse_url()
function.
PHP$url = "https://sabe.io/blog/php-domain-name-url";
$parsed = parse_url($url);
Now that we've parsed the URL, we just simply need to get the host
property from the $parsed
variable which will give us the domain name.
PHP$url = "https://sabe.io/blog/php-domain-name-url";
$parsed = parse_url($url);
$host = $parsed["host"];
echo($host);
BASHsabe.io
Keep in mind that you can also get the other properties, such as the scheme and path:
PHP$url = "https://sabe.io/blog/php-domain-name-url";
$parsed = parse_url($url);
$host = $parsed["host"];
$scheme = $parsed["scheme"];
$path = $parsed["path"];
echo($host);
echo($scheme);
echo($path);
BASHsabe.io
https
/blog/php-domain-name-url
Conclusion
In this post, we looked at how to extract the domain name from a URL using PHP.
Simply use the parse_url()
function to parse a URL, then get the host
property to get your domain name.
Thanks for reading and happy coding!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API