0

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";
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39

3 Answers3

2

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
OMi Shah
  • 5,768
  • 3
  • 25
  • 34
  • 1
    I love you.This was the most simple thing ever and I have been pulling my hair out looking for this. I have no idea why this was giving me so many issues, but thank you so much. This is exactly what I needed. – Jakob Glantz Aug 29 '20 at 16:46
1

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
  • 1
    Note: `split()` function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0. Alternatives to this function include: `preg_split()`, `explode()` and `str_split()` – jibsteroos Aug 29 '20 at 16:32
  • 1
    Better use [parse_str](https://www.php.net/manual/en/function.parse-str.php) on top or you will get problems when you have an url like `?page=whatever&tab=info`. [Example](https://phpize.online/?phpses=9347ab4820f129617eac3ee14388c6d4&sqlses=null) – SirPilan Aug 29 '20 at 16:51
1

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.

subhadip pahari
  • 799
  • 1
  • 7
  • 16