Processing Form Submissions
In Trongate, form submissions are typically handled by a dedicated method within your module's main controller file. This section will walk you through the process of handling form submissions securely and efficiently.
The Submit Method
Form processing is typically handled by a method named submit()
in your controller. Here's the typical structure for this method:
public function submit(): void {
$this->module('trongate_security');
$this->trongate_security->_make_sure_allowed();
$submit = post('submit', true);
if ($submit === 'Submit') {
// Set validation rules (covered in previous section)
// ...
$result = $this->validation->run();
if ($result === true) {
// Process valid form data
} else {
// Handle validation errors
}
}
}
Security Measures
The first two lines of the submit()
method ensure that only authorized users can submit the form:
$this->module('trongate_security');
$this->trongate_security->_make_sure_allowed();
This particular example restricts access to authorized site administrators only, using the _make_sure_allowed() method from the Trongate Security module. Your own code may have different authorization rules or even no authorization rules - for example - if you're working with a 'contact us' form.
Validation Check
After setting validation rules (as discussed here), run the validation tests with the following code:
$result = $this->validation->run();
If the $result
variable has a boolean value of true
, it means that the submitted form data has passed all of the form valiation tests.
Processing Valid Data
If validation passes, process the data. This typically involves inserting or updating records in the database. For example:
if ($result === true) {
$update_id = (int) segment(3);
$data = $this->get_data_from_post();
if ($update_id > 0) {
// Update an existing record
$this->model->update($update_id, $data, 'students');
$flash_msg = 'The record was successfully updated';
} else {
// Insert a new record
$update_id = $this->model->insert($data, 'students');
$flash_msg = 'The record was successfully created';
}
set_flashdata($flash_msg);
redirect('students/show/' . $update_id);
}
How Posted Data Is Retrieved
The get_data_from_post()
method is a custom function designed to retrieve form data. It utilizes Trongate's post() function to access values from the PHP superglobal array $_POST
, which contains all posted form fields. Here's an example implementation:
/**
* Get data from the form submission.
*
* @return array Data retrieved from the form submission.
*/
private function get_data_from_post(): array {
$data['username'] = post('username', true);
$data['first_name'] = post('first_name', true);
$data['last_name'] = post('last_name', true);
$data['email_address'] = post('email_address', true);
return $data;
}
This method creates an associative array where each key corresponds to a form field name, and each value is retrieved from the $_POST
superglobal array using the post() function.
The second parameter (true
) in the post() function is optional and activates data cleaning when set to true
. Here's how the function operates:
- Retrieval: The function checks if the specified field exists in the
$_POST
superglobal. If the field is not found, it returns an empty string. - Data Cleaning (Optional): When the second parameter is set to
true
, the function performs the following steps:- Trimming: Whitespace from the beginning and end of the value is removed using
trim()
. This ensures that any extraneous spaces around the data are eliminated. - Sanitization: The value is processed by
htmlspecialchars()
to convert special characters to HTML entities. This helps prevent potential security issues such as Cross-Site Scripting (XSS) attacks by neutralizing potentially harmful characters. - Type Conversion: If the sanitized value is numeric, the function attempts to convert it to the appropriate data type:
- If the value can be validated as a float, it is converted to a float.
- If the value can be validated as an integer, it is converted to an integer.
- If neither condition is met, the value remains a string.
- Trimming: Whitespace from the beginning and end of the value is removed using
By setting the second parameter to true
in the post() function, you ensure that each piece of form data is sanitized and potentially converted, enhancing the security and data integrity of your application. If the second parameter is omitted or set to false
, the raw value from $_POST
is returned without any processing.
Analyzing the Data Processing Code
Let's break down the code that processes valid form data:
if ($result === true) {
$update_id = (int) segment(3);
$data = $this->get_data_from_post();
if ($update_id > 0) {
// Update an existing record
$this->model->update($update_id, $data, 'students');
$flash_msg = 'The record was successfully updated';
} else {
// Insert a new record
$update_id = $this->model->insert($data, 'students');
$flash_msg = 'The record was successfully created';
}
set_flashdata($flash_msg);
redirect('students/show/' . $update_id);
}
Key Components:
- Determining the Operation:
The code checks for an
$update_id
in the URL's third segment:$update_id = (int) segment(3);
If present and greater than zero, it indicates an update operation. Otherwise, it's a new record insertion.
- Gathering Form Data:
The
get_data_from_post()
method collects all submitted form data:$data = $this->get_data_from_post();
This method typically returns an associative array of field names and their values.
- Database Operations:
Depending on whether it's an update or insert operation:
if ($update_id > 0) { $this->model->update($update_id, $data, 'students'); } else { $update_id = $this->model->insert($data, 'students'); }
For updates, the existing record is modified using update(). For inserts, a new record is created, using insert() and the new ID is captured.
- Flash Messages:
A success message is prepared using the set_flashdata() function:
$flash_msg = 'The record was successfully updated'; // or 'created' set_flashdata($flash_msg);
This message will be displayed to the user on the next page load.
- Redirection:
Finally, the user is redirected to a page showing the new or updated record. The redirect is initiated by usage of Trongate's redirect() function:
redirect('students/show/' . $update_id);
This prevents form resubmission and confirms the operation's success to the user.
- Always validate and sanitize user input.
- Use Trongate's Model class to prevent SQL injection.
- Implement CSRF protection (Trongate handles this automatically with its form helper functions).
- Be particularly cautious if you are rendering data that has been submitted by an untrusted user. For those instances, usage of the out() function is recommended.
- Use SSL/TLS for handling sensitive information.
By following these guidelines and using Trongate's built-in features, you can ensure secure and effective form processing in your applications.