Сегодня я напишу простой класс для «очистки» данных. Дело в том, что пользововать может ввеси некоректные данные как ненамеренно, так и злонамеренно. Например когда я возьмусь за написание класса Route. Этот класс будет брать данные из адресной строки браузера и по ней определять какой конкретно модуль должен запуститься в данный момент. Пользователь может ввести туда какой-нибудь вредоносный код и что-нибудь мне сломать. Этого я постораюсь избежать. Так же будут в формы для ввода информации. Регистрация пользователя, комметарии и т.д.
Где-то читал, что вообще любые данные приходящие от пользователя обязательно должны проверяться.
Полагаю каждый раз писать одинаковый код для проверки данных приходящих от пользователя не очень интересно, поэтому я и решил написать класс DataCleaner.
При написании своего класса я буду использовать стандартные функции PHP
trim — удаляет пробелы в начале и в конце строки. Это на тот случай если при вводе логина или пароля пользователь ввёл лишний пробел. Например при копировании из письма. Такое случается довольно часто.
strip_tags — удаляет все HTML и PHP теги. Злоумышленнику будет сложней ввести вредоносный код.
htmlspecialchars — преобразовывает специальные символы в HTML сущности.
Код самого класса получился совсем небольшой:
<?php
class DataCleaner
{
public static function dc($data)
{
$data = trim($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
return $data;
}
}
Таким образом вместо вызова трёх стандартных функций PHP каждый раз когда мне это необходимо буду писать только одну строку
$name = \DataCleaner::dc($_POST['name']);
Уже хотел было как обычно написать продолжение следует, но внезапно мозг поразила мысль о том, что я далеко не всё учёл.
Пришла на ум простая ситуация.
Пусть администратор разрешил регистрироваться пользователям от 14 до 99 лет. Запрашиваем у пользователя сколько ему лет. Пользователь вводит число, допустим 1. Дальше мне необходимо проверить число на валидность. Во первых даже не смотря на то, что дети сейчас очень рано начинают пользоваться компьютерами, подобный возраст заставляет усомниться в правильности заполнения поля возраст пользователем. Здесь вероятно закралась какая-то ошибка. Может пользователь не нажал на клавиатуре ещё какую-то цифру? Необходимо как-то сравнить число которое ввёл пользователь с диапазоном разрешённых чисел.
И вот тут первая проблема.
$age = \DataCleaner::dc(1);
var_dump($age);
вернёт string '1' (length=1)
То есть результат будет строка а не число. Помню что PHP относится довольно лояльно к подобному и вполне может разрешать математические операции типа
$summ = 2 + '2';
var_dump($summ);
вернёт int 4
Но я чуствую некую неуверенность в том, что это верно запишется в базу данных и предполагаю наличие проблемм в будующем.
Этого мне не хочется и ближайший вечер или 2 буду работать над решением этом проблемы.
Продолжение следует…
[…] предыдущей статье я написал класс для очистки данных получаемых […]
Taxi moto line
128 Rue la Boétie
75008 Paris
+33 6 51 612 712
Taxi moto paris
What i do not understood is actually how you’re no longer really a lot more smartly-appreciated than you may be now.
You are so intelligent. You already know therefore
significantly in the case of this topic, made me personally consider it from
so many numerous angles. Its like men and women are not interested except
it’s one thing to do with Girl gaga! Your individual stuffs excellent.
Always handle it up!
Warning: Vernon Hills, IL and Libertyville, IL and surrounding 50 miles radius area is in active war zone ! Towns are held hostage by UK agents, Russian spies, Indian spies, Mexican spies, Chinese spies, and other Hispanic spies Cayla Hillier Shipp
Good answers in return of this issue with firm arguments and explaining all on the topic of that. Felecia Timmy Caldera
I gotta favorite this site it seems very useful invaluable Alexine Silvanus Bunker
Everything is very open with a clear explanation of the challenges. It was definitely informative. Your site is extremely helpful. Thank you for sharing! Karlotta Myca Oly
There is clearly a bunch to identify about this. I assume you made certain nice points in features also. Yasmeen Jerri Krawczyk
Great article. I learn something much more tough on various blogs day-to-day. It will constantly be promoting to review material from various other writers as well as exercise a little something from their shop. I?d prefer to make use of some with the material on my blog site whether you don?t mind. Natually I?ll offer you a web link on your web blog. Thanks for sharing. Sella Fulton Nestor
This blog post is extremely fascinating from starting line to finish. Blisse Zeb Brunn
Hi my friend! I want to say that this article is amazing, great written and include approximately all vital infos. I would like to see extra posts like this. Julienne Jone Pierre
Lindsay Preston is a multi-certified life coach for go-getter women who have good lives but want great lives. Elsa Rube Maxama
Now I am going to do my breakfast, once having my breakfast coming yet again to read further news. Lea Roland Rothschild
A lot of thanks for every one of your effort on this site. My niece enjoys making time for investigations and it is obvious why. Many of us notice all regarding the dynamic manner you convey vital suggestions through the web site and invigorate response from others about this area so our favorite daughter has been discovering a whole lot. Enjoy the remaining portion of the year. You are carrying out a dazzling job. Neille Derby Thilda
Fabulous analysis for even a laymen to understand how well modern technology can be used to overcome the health challenges created by COVID-19. This article will be useful to many authorities to expand their horizons in finding creative solutions to control the spread of the pandemic. Layla Chas Joachim
I gotta bookmark this website it seems handy very beneficial Valentine Zackariah Symon
I as well as my guys have been digesting the nice information from your web page while the sudden came up with a horrible feeling I had not expressed respect to the site owner for those secrets. Most of the women came certainly joyful to read them and have now sincerely been making the most of these things. Many thanks for actually being very kind and for having this form of high-quality ideas most people are really desperate to discover. My personal sincere regret for not expressing gratitude to you sooner. Fanni Anselm Wolfgram