Skip to content
Advertisement

Getting the second part of a URL through PHP

I’m trying to setup a page that pulls just a part of the URL but I can’t even get it to echo on my page.

Since I code in PHP, I prefer dynamic pages, so my urls usually have “index.php?page=whatever” I need the “whatever” part only.

Can someone help me. This is what I have so far, but like I said, I can’t even get it to echo.

$suburl = substr($_SERVER["HTTP_HOST"],strrpos($_SERVER["REQUEST_URI"],"/")+1);

and to echo it, I have this, of course:

echo "$suburl";

Advertisement

Answer

your url is index.php?page=whatever and you want to get the whatever from it

if the part is after ? ( abc.com/xyz.php?……) , you can use $_GET[‘name’]


for your url index.php?page=whatever

use :

$parameter= $_GET[‘page’]; //( value of $parameter will be whatever )


for your url index.php?page=whatever&no=28

use :

$parameter1= $_GET[‘page’]; //( value of $parameter1 will be whatever )

$parameter2= $_GET[‘no’]; //( value of $parameter2 will be 28 )


please before using the parameters received by $_GET , please sanitize it, or you may find trouble of malicious script /code injection

for url : index.php?page=whatever&no=28

like :

if(preg_match("/^[0-9]*$/", $_GET['no'])) {
   $parameter2= $_GET['no'];
}

it will check, if GET parameter no is a digit (contains 0 to 9 numbers only), then only save it in $parameter2 variable. this is just an example, do your checking and validation as per your requirement.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement