segment()

function segment(int $num, ?string $var_type = null): mixed

Description

Retrieves a specific segment from the current URL. Unlike earlier framework conventions that implicitly injected URL values into controller methods, segment() makes URL input explicit, predictable, and secure.

Parameters

Parameter Type Description Default
$num int The position of the URL segment to retrieve (starting from 1). N/A
$var_type string|null Optional. If provided, the segment value is coerced to this PHP data type using settype(). This enables type safety at the point of retrieval. null

Return Value

Type Description
mixed The value of the requested URL segment. Returns an empty string if the segment does not exist.

Basic Example

PHP
echo segment(1);
// URL: https://example.com/blog/view/hello-world
// Output: blog

Type-Safe Numeric ID

Passing a second argument enables automatic type coercion. This is especially useful for numeric identifiers and makes SQL injection attempts ineffective.

PHP
public function profile() {
  $user_id = segment(3, 'int');

  if ($user_id <= 0) {
    http_response_code(400);
    die('Invalid user ID');
  }

  $user = $this->model->get_user($user_id);
}

String Slug Example

Explicitly fetching string values improves readability and makes the source of external input immediately obvious.

PHP
public function show() {
  $slug = segment(3, 'string');

  if ($slug === '') {
    redirect('blog');
  }

  $post = $this->model->get_by_slug($slug);
}

Boolean Flag Example

Boolean coercion is useful for toggle-style routes where values such as 1 and 0 are expected.

PHP
public function toggle() {
  $active = segment(3, 'bool');
  $this->model->set_status($active);
}

Supported Data Types

  • 'int' - integer values
  • 'float' - decimal values
  • 'bool' - boolean values
  • 'string' - string values
  • 'array' - advanced or edge cases

By combining explicit URL access with native PHP type coercion, segment() encourages safer, clearer, and more maintainable controller code.