0

This is my url form:

http://dev.test.de/profile/id/

I am trying to echo the id of the current url.

$parts = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$path_parts= explode('/', $parts[path]);
echo $user = $path_parts[2];

But it says:

Warning: Illegal string offset ‘path’

thank you

Marc Ster
  • 2,276
  • 6
  • 33
  • 63
  • 1
    call explode as `$path_parts = explode('/', $parts);` there is no index such `$parts[path]` . `$parts` is a string. you are exploding it into an array – epipav Aug 07 '14 at 08:28
  • Already answered here: http://stackoverflow.com/questions/2273280/how-to-get-the-last-path-in-the-url – Gestudio Cloud Aug 07 '14 at 08:28

4 Answers4

1

Your $parts variable is a string.

$parts = 'http://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
$path_parts= explode('/', $parts);
echo $user = $path_parts[4];

This will return the id.

peter.babic
  • 3,214
  • 3
  • 18
  • 31
1

This, should work for you.

$parts = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$path_parts= explode('/', $parts);
echo $user = $path_parts[4];

it is the 4th index because

  • [0] contains "http:"
  • [1] contains ""
  • [2] contains "dev.test.de"
  • [3] contains "profile"
  • [4] contains "id"
epipav
  • 339
  • 2
  • 14
0

try this

$parts = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$path_parts= explode('/', $parts);
echo $user = $path_parts[2];
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

There are two problems in your example.

$parts = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$_SERVER is a super global array and HTTP_HOST is one of it's indices. As this is an associative array you need to enclose the index name with a pair of either single quotes, or double quotes. So it should be $_SERVER['HTTP_HOST'], and because this is inside a string you need to use {} to interpolate the variable/array name. So it looks like:

$parts = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

or simply separate them as

$parts = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

Your second problem is:

$path_parts= explode('/', $parts[path]);

as far as your code goes $parts is a string not an array, so $parts[path] has no meaning here. It should be:

$path_parts= explode('/', $parts);