user3149569
user3149569

Reputation: 147

php - url split up produces an empty 0 index

So i'm creating a php application and is currently working on checking the url.

i am running on the build in development server from php, with the public directory as the root

php -S localhost:8080 -t public/

when i explode the url, i do it like this

$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($url, '/'));

but if for example type in the url:

localhost:8080/index/test

the content of $segments is the following:

echo $segments[0]; // empty,
echo $segments[1]; // index
echo $segments[2]; // test

Why is the first index always there, and empty?

unset($segments[0]);

solves the problem, but i would like to know why it occours.

Upvotes: 1

Views: 81

Answers (1)

sidyll
sidyll

Reputation: 59277

If your URL starts with /, exploding on that character will create an empty item at the beginning (there is nothing before the first separator). In this case, since you're already trimming / at the end with rtrim(), it will be a simple fix: use trim() instead to trim both sides:

$segments = explode('/', trim($url, '/'));

Upvotes: 2

Related Questions