Image

Knowledge base → Variables in php to get the URL or part of it

[Scripts]
Date of publication: 11.10.2023

To retrieve URL parameters or its individual parts, use the following PHP constructs:

1. Retrieving the URL

https://domain.tld/temp/url.php
<?php
    echo $_SERVER['REQUEST_URI'];
?>
/temp/url.php

2. Retrieving the folder from the URL

https://domain.tld/temp/url.php
<?php
    $parts = explode("/", $_SERVER['REQUEST_URI']);
    echo $parts[1];
?>
temp

3. Retrieving the last part of the URL

https://domain.tld/temp/url.php
<?php
    echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
?>
url.php

3.1 Second method for retrieving the last part of the URL

https://domain.tld/temp/url.php
<?php
    $parts = explode("/", $_SERVER['REQUEST_URI']);
    echo $parts[2];
?>
url.php

4. Retrieving the directory where the script is located

https://domain.tld/temp/url.php
<?php
    echo dirname(__FILE__);
?>
/var/www/vhosts/domain.tld/httpdocs/temp

4.1 Retrieving the root directory

https://domain.tld/temp/url.php
<?php
    echo dirname(dirname(__FILE__));
?>
/var/www/vhosts/domain.tld/httpdocs

5. Retrieving the domain name from the URL

https://domain.tld/temp/url.php
<?php
    echo $_SERVER['HTTP_HOST'];
?>
domain.tld

6. Retrieving the IP address of the remote device

https://domain.tld/temp/url.php
<?php
    echo $_SERVER['REMOTE_ADDR'];
?>
xx.ip.xx.ip




No Comments Yet