How to get the current URL and filename using PHP
Updated: 07-Aug-2024 / Tags: PHP Lang Reference / Views: 79 - Author: George
Introduction
In this article we are going to fetch the current URL and filename to load a specific stylesheet to a specific page using PHP.
Working with php, usually means that we are structuring our html code in a way, that looks like a template. Most of the times we have a file called head.php which contains our meta tags, our stylesheet link tags, maybe google fonts, or javascript code.
Something like this.
<!-- head.php -->
<meta name="description" content="<?php echo $description ?>">
<meta name="keywords" content="<?php echo $keywords ?>">
<script src="some-script.js"></script>
<link rel="stylesheet" href="main.css">
We include the head.php in every page inside the head tags, so when we need to make a change to the file, the change will affect the whole website, and it saves us a lot of work.
<head>
<?php include "includes/head.php" ?>
</head>
But what if, we need a specific stylesheet for a specific page. Let's say we have an about.php page, and we have to load the about.css stylesheet for that page.
A quick solution is to check if the about.php page is loaded in the browser, and if it is we serve the about.css stylesheet.
All the information we need to do the task, is in the browser's url.
The superglobal $_SERVER array has a key named 'SCRIPT_NAME', this key contains the current script's path. Let's echo out the variable to see what we get.
// head.php
echo $_SERVER['SCRIPT_NAME'];
We see the current file path, and at the end of the path we have the file's name. In this case it's the about.php page.
If you want to see the $_SERVER array's content, just run a var_dump($_SERVER).
Now we have to extract the file name so we can run a comparison. PHP has a built in function called basename(). The basename function takes as an argument a file path, and returns the file's name.
$file_name = basename($_SERVER['SCRIPT_NAME']);
echo $file_name;
Running the above script we get the file's name.
Now we can run an if statement inside the head.php file, and check if the current page is the about.php page.
If so we will load the about.css stylesheet, else for every other page we load the main.css file.
if ($file_name == "about.php") {
?>
<link rel="stylesheet" href="about.css">
<?php
}else{
?>
<link rel="stylesheet" href="main.css">
<?php
}
Summary
In this tutorial we saw how to use the $_SERVER['SCRIPT_NAME'] variable to get the current URL, and combined with the basename() function we extracted from the URL the current file name.
Thanks for reading, i hope you find this quick article helpful.
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉