Getting the second part of a URL through PHP

102 Views Asked by At

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";
3

There are 3 best solutions below

0
On BEST 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.

2
On

You can use basic PHP function parse_url for example:

<?php

$url = 'http://site.my/index.php?page=whatever';

$query = parse_url($url, PHP_URL_QUERY);

var_dump(explode('=', $query));

Working code example here: PHPize.online

1
On

If you need to get the value of the page parameter, simply use the $_GET global variable to access the value.

$page = $_GET['page']; // output => whatever