I have a question about the PHP $_SERVER[];
In the root directory I have a folder named site. In this folder I have an index.php file
The code below is written in the index file
<?php
echo $_SERVER['REQUEST_URI'];
?>
If the user goes to https:www.example.com/site the request_uri is /site
If the user goes to https:www.example.com/site/page the request_uri is /site/page
So my question:
Is it possible to get the REQUEST_URI from the directory where the code is written?
Get request uri minus the upper folders the folder where the code is written is the start.
For example
If the user goes to https:www.example.com/site the request_uri is /
If the user goes to https:www.example.com/site/page the request_uri is /page
My Answer:
Yes, you can achieve this by using the `basename()` function in PHP. Here's an example code snippet that demonstrates how to get the request URI relative to the directory where the code is written:
php
$basePath = dirname($_SERVER['SCRIPT_NAME']);
$requestUri = str_replace($basePath, '', $_SERVER['REQUEST_URI']);
echo $requestUri;
?>
In this code snippet, `dirname($_SERVER['SCRIPT_NAME'])` will give you the directory path where the script is located, and then `str_replace()` is used to remove this base path from the `REQUEST_URI`, giving you the request URI relative to the directory where the code is written.
Rate this post
3 of 5 based on 9904 votesComments