Skip to content

Instantly share code, notes, and snippets.

@d1i1m1o1n
Last active March 15, 2023 06:03
Show Gist options
  • Save d1i1m1o1n/44b6aeb35bd959d317c6 to your computer and use it in GitHub Desktop.
Save d1i1m1o1n/44b6aeb35bd959d317c6 to your computer and use it in GitHub Desktop.
Проверка номера СНИЛС
<?php
if(!empty($_POST)){
// Массив сообщений об ошибках
$error = array();
// Удаляем тире и пробелы
$number = str_replace(array(" ", "-"),
array("", ""),
$_POST['number']);
$pattern = "|^\d{11}$|";
if(!preg_match($pattern, $number)){
$error[] = "Введите число, содержащее 11 символов";
}
// Контрольная сумма
$control = substr($number, -2);
// Число
$number = substr($number, 0, 9);
// Проверяем можно ли подсчитывать
// контрольную сумму
if($number < "001001998"){
$error[] = "Подсчет контрольной суммы производить нельзя";
}
// Если ошибок нет, вычисляем контрольную сумму
if(empty($error)){
// Вычисляем контрольную сумму
$result = 0;
$total = strlen($number);
for($i = 0; $i < $total; $i++){
$result += ($total - $i) * $number[$i];
}
// Корректируем контрольное число
if($result == 100 || $result == 101) $result = "00";
if($result > 101) $result %= 101;
// Проверчем контрольное число
if($result == $control) echo "Контрольное число корректное";
else echo "Контрольное число не корректное";
}
// Если есть ошибки выводим их
echo "<div style='color:red'>";
echo implode("<br>", $error);
echo "</div>";
}
?>
<form method='post' action=''>
<input type='text' name='number' value='<?php echo htmlspecialchars($_POST['number'], ENT_QUOTES); ?>' />
<input type='submit' value='Обработать'>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment