Skip to content

Instantly share code, notes, and snippets.

@jackhftang
Last active February 16, 2019 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackhftang/1910a56088553194ea4cb7dc10f54524 to your computer and use it in GitHub Desktop.
Save jackhftang/1910a56088553194ea4cb7dc10f54524 to your computer and use it in GitHub Desktop.
The infamous php if hell refactoring
<?php
function register()
{
if (empty($_POST)) {
return register_form();
}
if (($msg = validate($_POST)) !== null) {
$_SESSION['msg'] = $msg;
return register_form();
}
createUser();
$_SESSION['msg'] = 'You are now registered so please login';
header('Location: ' . $_SERVER['PHP_SELF']);
exit();
}
function validate($input)
{
if (!$input['user_name']) {
return 'Empty Username';
}
if (!$input['user_password_new']) {
return 'Empty Password';
}
if ($input['user_password_new'] !== $input['user_password_repeat']) {
return 'Password do not match';
}
if (strlen($_POST['user_password_']) <= 5) {
return 'Password must be at least 6 characters';
}
if (!preg_match('/^[a-z\d]{2,64}$/i', $input['user_name'])) {
return 'Username must be only a-z, A-Z, 0-9';
}
$user = read_user($_POST['user_name']);
if (isset($user['user_name'])) {
return 'Username already exists';
}
if (!$input['user_email']) {
return 'Email cannot be empty';
}
if (!strlen($input['user_email']) < 65) {
return 'Email must be less than 64 characters';
}
if (filter_var($input['user_email'], FILTER_VALIDATE_EMAIL)) {
return 'You must provide a valid email address';
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment