post()

function post(string|bool|null $field_name = null, bool $clean_up = false, bool $cast_numeric = false): string|int|float|array

Description

Retrieves submitted form data from POST requests, JSON payloads, or multipart form data. This unified function handles all incoming request data with support for nested structures and automatic parsing.

Parameters

Parameter Type Description
$field_name string|bool|null (optional) Field name to retrieve (string), null for all raw data, or true for all cleaned data. Default is null.
$clean_up bool (optional) Trim whitespace from ends and collapse multiple spaces within the string. Default is false.
$cast_numeric bool (optional) Convert purely numeric strings (e.g., "42", "3.14") to integers or floats. Default is false.

Return Value

Type Description
string|int|float|array Request data as string, number, or array depending on parameters and input structure.

Understanding the $clean_up Parameter

When $clean_up is set to true, the post() function performs two operations on string values:

  1. Trimming: Removes whitespace from the beginning and end of strings.
  2. Collapsing: Reduces multiple consecutive spaces, tabs, or line breaks to a single space.

This cleaning applies recursively to nested arrays.

Examples of $clean_up Behavior:

PHP
// Input field value (message): "   Hello    World   \n\n"
$raw = post('message');          // Returns: "   Hello    World   \n\n" (Raw, spaces preserved)
$clean = post('message', true);  // Returns: "Hello World" (Trimmed and collapsed)

// Input array value (items): [" item1 ", " item2    item3 "]
$raw_array = post('items');      // Returns: [" item1 ", " item2    item3 "]
$clean_array = post('items', true); // Returns: ["item1", "item2 item3"]

Basic Retrieval

Get All or Specific Data

PHP
// Get all data as a raw array (no cleaning)
$all_data = post();

// Get all data with recursive whitespace cleaning
$clean_data = post(true);

// Get a specific field's raw value
$username = post('username');

// Get a specific field's cleaned value
$clean_name = post('username', true);

// Get cleaned value and cast it to a number (if numeric)
$quantity = post('quantity', true, true);

Numeric Casting

When $cast_numeric is true, purely numeric strings are converted to their appropriate PHP types:

PHP
// Numeric strings are cast:
$int_val = post('field_1', false, true); // Input: "42" → Output: 42 (integer)
$float_val = post('field_2', false, true); // Input: "3.14" → Output: 3.14 (float)

// Non-numeric strings are untouched:
$str_val = post('field_3', false, true); // Input: "abc" → Output: "abc" (string)
$zero_prefix = post('field_4', false, true); // Input: "0123" → Output: "0123" (string - preserves leading zero)

Nested Data Access

The post() function supports two methods for accessing data within nested arrays or objects:

Dot Notation (For JSON Payloads)

PHP
// Assume POST body is JSON: {"user": {"profile": {"name": "John", "age": "25"}}}
$name = post('user.profile.name'); // "John"
$age = post('user.profile.age', true, true); // 25 (integer)

Bracket Notation (For Standard Form Arrays)

PHP
// Assume POST data is: colors[0]=red&colors[1]=blue
$first_color = post('colors[0]'); // 'red'
$second_color = post('colors[1]'); // 'blue'
$all_colors = post('colors'); // ['red', 'blue']

Supported Data Formats

post() automatically handles multiple content types:

Content Type Source Notes
application/x-www-form-urlencoded Standard HTML forms Uses $_POST superglobal
multipart/form-data Forms with file uploads Uses $_POST superglobal
application/json API requests, AJAX Automatically parsed from raw input
Other formats Custom APIs Parsed with parse_str()

JSON Error Handling: Malformed JSON payloads will throw an Exception. Wrap API endpoints in try-catch blocks when processing JSON input.

SECURITY NOTE: The post() function only retrieves and cleans data; it does NOT escape it for HTML output. Always use htmlspecialchars() or Trongate's out() function before displaying user data in views to prevent XSS vulnerabilities.

Practical Examples

Form Processing in Controller

PHP
public function submit(): void {
    // Retrieve, clean, and cast data in one step
    $data['username'] = post('username', true);
    $data['email'] = post('email', true);
    $data['age'] = post('age', true, true); 
    
    // Checkbox conversion (requires manual cast)
    $data['newsletter'] = (int) (bool) post('newsletter', true); 
    
    $this->db->insert($data, 'users');
}

API Endpoint with JSON

PHP
public function api_create(): void {
    try {
        // Dot notation is ideal for structured JSON payloads
        $title = post('article.title', true);
        $content = post('article.content', true);
        
        // ... process API request
    } catch (Exception $e) {
        // Handle JSON parsing errors
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON payload']);
    }
}

Performance: Request data is parsed once and cached for the duration of the request. Subsequent calls to post() within the same request use the cached data.

Error Handling and Missing Fields

  • Missing fields return an empty string ('')
  • Empty requests return an empty array
  • Nested paths that don't exist return empty string
  • Malformed JSON throws an Exception

Debugging

Use the json() helper function to inspect submitted data during development:

PHP
// View all raw submitted data
json(post());

// View cleaned, nested data
json(post('user.profile', true));

// View data and stop script execution
json(post(), true);

Combining post() with json() makes form debugging straightforward. Use json(post(), true) to immediately see all submitted data and halt further script execution.