Custom Content Management System (CMS)

How to generate absolute links & relative links with PHP (and why they're useful!)

Scott Dallas @

Before we dive straight into the PHP and what it's useful for, let's get a quick refresher on what absolute links and relative links are:

Absolute Link: An absolute link is an entire hyperlink that includes http or https in the URL, the domain, and the page name or directory the content is in if there is any. For example:

https://www.cuteword.org/contact/

Relative Link:A relative link ignores most of the information other than the final part of the URL that shows the page or directory of the content after the domain. For example:

contact/

So, now that we know that, let's see the PHP for a full absolute link! I do a little cheat to achieve this because when I'm making a site I always know whether or not it's going to be http (insecure) or https (secure). Almost all public websites are secure these days so when in doubt it's probably https. Just look at the address bar and you'll be able to tell what you're working with if you weren't the one that initially set it up. That being said, here is the PHP code:

$absLink = "https".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

You can name your variable whatever you'd like. I've gotten used to $absLink myself. Also, change the https to http or vice versa depending on your needs. You also don't necessarily need to have the http in the string variable at all to use it the way I do. More commonly, I only use this code:

$relLink = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

Now you're able to use that information to run an if else statement to generate different things on your page depending on what page a user is on. WordPress does a similar thing using is_page("X") where X is the page, post, or product ID. They also do this with a lot other variables, but you can achieve the exact same end result just by checking the URL of a page. Let me show you what I mean:

if ( strpos($relLink('contact') ) { echo "The URL contains the word contact."; } else { echo "The URL does not contain the word contact."; }

Code TricksPHP

absolute link, absolute links, relative link, relative links, php absolute link, php relative link, php, php code, code tricks, php code tricks, useful code, free code, code snippets

28
29
36
30
28
27
31
32
28
28
Views Up Votes Down Votes
155 0 0

Leave a Reply