Secure submitting of forms October 23, 2024
If you use a form to submit data that is stored in the database on your site it is recommended to use XRSF tokens to avoid unauthorized requests and prevent Cross Site Request Forgeries.
Here is a basic form that submits some data:
<form id="myform" action="<?php echo html_encode(getRequestURI()); ?>" method="post" accept-charset="UTF-8">
<?php XSRFToken('myformaction'); // use a unique name of the action ?>
<input type="text" name="mytext" value="">
<input type="submit" value="Submit">
</form>
The line <?php XSRFToken('myformaction'); ?> prints an input field with the token. If you need the token itself, in a URL query for example, you can use $token = getXSRFToken('myformaction');.
On processing the form data you would also have to check that XSRFtoken using XSRFdefender('myformaction');
If the token does not match this will stop the process. If it succeeds you can afterwards fetch your $_POST or $_GET data.
Always sanitize the data before using it:
$mytext = sanitize($_POST['mytext'], 3);
If you know your value will be numeric you can also use:
$mytext = sanitize_numeric($_POST['mytext']);
If you need to output fetched and sanitized data always use html_encode().
This text by www.zenphoto.org is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Code examples are released under the GPL v2 or later license
For questions and comments please use the forum or discuss on the social networks.