Problem with POST data types |
After update from 4.4.7 to 4.5 i got erros when i POSST data via AJAX, and validate data with custom function like
public function validateRange (int $number): bool { return ($number > 5 && $number < 10); } before it worked properly i got by POST variable number ["number "]=> string(1) "7" but now i got " Argument #1 ($number) must be of type int, string given" How prevent it, instead converting all data before validation? is bug of 4.5 version CI? Or is it possible auto convert POST data to exact type of data?
Sorry this is not a bug, but an intended behavior of PHP.
Because you specify int to $number, and "7" is not an int value. Quick workaround is just remove the type "int" in the function.
(04-07-2024, 07:23 PM)kenjis Wrote: Sorry this is not a bug, but an intended behavior of PHP. But before update to 4.5 its worling correctly, i didn`t update php Is only one way after get POST cast types every time?
It was converted to int implicitly by PHP.
But in 4.5.0 "declare(strict_types=1);" has been added to most of the framework codebase. See https://www.php.net/manual/en/language.t...ons.strict Because if devs expect int values, string values should not pass the validation. So now it is not converted implicitly, and causes TypeError. > Sorry this is not a bug, but an intended behavior of PHP. This sentence was not precise. PHP's default behavior is to convert implicitly, but now we use strict mode for strict type coding.
(04-08-2024, 01:47 AM)kenjis Wrote: It was converted to int implicitly by PHP. what is better solution? Send data like JSON? but in this way i can use $this->request->getPost('id') and need rewrite all logick in project. Or i need conver data on the server after receiving? Any way i can`t use $this->request->getPost('id') is any function if i get jSON, put data in POST automaticly? For example i have simple form send by POST in server i get $this->request->getPost('id'), $this->request->getPost('type') ect all type of course string by default, before validate i need set correct types for each field?
First of all, you need to define what values are really valid in this case.
Then validate user input (string value if it is POSTed). If it is valid, then convert to int. PHP Code: function validateRange(int $number): bool { https://3v4l.org/1EnTK
(04-08-2024, 01:55 PM)kenjis Wrote: First of all, you need to define what values are really valid in this case. Try load this function like this 'number' => [ 'label' => ' ', 'rules' => 'required|validateRange' ] |
Welcome Guest, Not a member yet? Register Sign In |