function validateForm(&$errors) { global $firstname, $lastname, $day, $month, $year; $errors = []; foreach (['firstname', 'lastname', 'day', 'month', 'year'] as $value) { if (!validateRequired(${$value})) { $errors[$value][] = "{$value} is required"; } if (!validateString(${$value})) { $errors[$value][] = "{$value} must be a string"; } } return empty($errors); }
function validateForm(&$errors) { global $product, $brand, $size, $gender, $quantity; $errors = []; foreach (['product', 'brand', 'gender', 'size', 'quantity'] as $value) { if (!validateRequired(${$value})) { $errors[$value][] = "{$value} is required"; } if (!validateString(${$value})) { $errors[$value][] = "{$value} must be a string"; } } return empty($errors); }
function getFormInput($inputName, $sqlQueryStart, $sqlQueryEnd, $inputType) { $queryName = ''; if (isset($_GET[$inputName]) && $_GET[$inputName] != '' && $_GET[$inputName] != "All") { $input = clean_input($_GET[$inputName]); if ($inputType == "Interger") { validateInteger($input, $inputName . "Error"); } elseif ($inputType == "String") { validateStringLength($input, $inputName . "Error"); validateString($input, $inputName . "Error"); } $queryName = $sqlQueryStart . $input . $sqlQueryEnd; } return $queryName; }
function validateForm(&$errors) { global $character; $errors = []; foreach (['character'] as $value) { if (!validateRequired(${$value})) { $errors[$value][] = "{$value} is required"; } if (!validateString(${$value})) { $errors[$value][] = "{$value} must be a string"; } } if (!validateEqualString($character, 1)) { $errors['character'][] = "You must enter a single character"; } return empty($errors); }
function validateForm(&$errors) { global $username, $password, $confirmPassword; $errors = []; foreach (['username', 'password'] as $value) { if (!validateRequired(${$value})) { $errors[$value][] = "{$value} is required"; } if (!validateString(${$value})) { $errors[$value][] = "{$value} must be a string"; } } if (!validateRequired($confirmPassword)) { $errors['confirmPassword'][] = '"Confirm Password" is required'; } if (!validateString($confirmPassword)) { $errors['confirmPassword'][] = "\"Confirm Password\" must be a string"; } if (!validateLongerOrEqualString($username, 6)) { $errors['username'][] = "Username must be minimum 6 symbols long"; } if (!validateLongerOrEqualString($password, 8)) { $errors['password'][] = "Password must be minimum 6 symbols long"; } if (!validateNonAlphaNumeric($password)) { $errors['password'][] = 'Password must contain at least 1 non alphanumeric character'; } if (!validateLongerOrEqualString($confirmPassword, 8)) { $errors['confirmPassword'][] = "Password must be minimum 6 symbols long"; } if (!validateNonAlphaNumeric($confirmPassword)) { $errors['confirmPassword'][] = 'Password must contain at least 1 non alphanumeric character'; } if (strcmp($password, $confirmPassword) !== 0) { $errors['confirmPassword'][] = 'Confirm Password and Password must be equal'; } return empty($errors); }
$title = validateString('tytuł', $postVars['title'], 4, 64); $description = validateString('opis', $postVars['description'], 6, 2048); $result = $thread->update($id, $title, $description); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->post('/id/:id/notify', validatePrivileges(array('administrator')), function ($id) use($app, $thread) { try { $postVars = $app->request->post(); // Walidacja danych if (empty($postVars['notify_text'])) { throw new Exception('Niekompletne dane.', 400); } $notify_text = validateString('wiadomość', $postVars['notify_text'], 6, 2048); $result = $thread->notify($id, $notify_text); $email_to = implode(',', $result); $subject = 'Powiadomienie'; $message = $notify_text . " \nJeśli nie chcesz otrzymywać wiadomości e-mail, zaloguj się na www.bariery.wroclaw.pl i wycofaj subskrypcję dla zgłoszeń."; $headers = 'From: admin@bariery.wroclaw.pl' . "\r\n" . 'Reply-To: no-reply@bariery.wroclaw.pl' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $subject, $message, $headers); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->delete('/id/:id', validatePrivileges(array('administrator')), function ($id) use($app, $thread) { try { $result = $thread->delete($id); jsonSuccess($app, $result);
if (isset($_SESSION['userId']) and is_numeric($_SESSION['userId'])) { // Load user as object, from SQL by id $loggedUser = $delegate->userGetById(abs(intval($_SESSION['userId']))); // If exists a logged user if (is_numeric($loggedUser->id)) { redirect('./editor.php'); } /** * [2] Cookie method * Check if user cookie is set */ } elseif (isset($_COOKIE['biscuit'])) { // Decode the cookie data $userCookie = packer($_COOKIE['biscuit'], PACKER_UNPACK); // Validate data if (validateEmail($userCookie['email'], null) and validateString($userCookie['password'], null, 1)) { // Load user as object, from SQL by id $loggedUser = $delegate->userGetByEmailAndCryptedPassword($userCookie['email'], $userCookie['password']); // If user is an object if (is_object($loggedUser)) { $_SESSION['userId'] = $loggedUser->id; redirect('./editor.php'); } } } ?> <!DOCTYPE html> <html> <?php
<?php /* Use PHP 5.3. Task: Develop a function which validates string looking like this "[{}]" Every opening bracket should have corresponding closing bracket of same type "[{}]" is a correct string, "[{]}" is malformed one. Usage: <your host>/validateString.php?i={input string} Example: <your host>/validateString.php?i={[{{} */ if (isset($_GET['i'])) { $inputString = $_GET['i']; echo "'" . $inputString . "' is "; echo validateString($inputString) ? "correct" : "incorrect"; } else { die('invalid URL'); } function validateString($inputString) { $valid = false; $matches = null; preg_match_all("/[\\[\\{\\}\\]]/", $inputString, $matches); $bracket = $matches[0]; $loop = round(count($bracket) / 2); $bracket_String = implode('', $bracket); while ($loop--) { $bracket_String = preg_replace("/(\\[\\])|(\\{\\})/", "", $bracket_String); // var_dump($bracket_String); if (!preg_match("/[\\[\\{\\}\\]]/", $bracket_String)) { $valid = true;
function validateType($target, $value, $type) { switch ($type) { case "boolean": return is_bool($value); break; case "int": return is_int($value); break; case "float": return is_float($value); break; case "hex": return ctype_xdigit($value); break; case "string": return validateString($target, $value); break; case "date": global $date_format; return dateFormat($value, $date_format, ""); break; case "hour": return validateHour($value); break; case "url": return validateUrl($value); break; case "email": return validateEmail($value); break; default: return false; } }
} catch (Exception $e) { jsonError($app, $e); } }); $app->post('/id/:id/edit', validatePrivileges(array('user', 'administrator')), function ($id) use($app, $comment) { try { $c = $comment->getByID($id); if ($GLOBALS['privileges'] == 'user' && $GLOBALS['user_id'] != $c['user_id']) { throw new Exception('Nie jesteś autorem komentarza.', 403); } $postVars = $app->request->post(); // Walidacja danych if (empty($postVars['comment'])) { throw new Exception('Niekompletne dane.', 400); } $text = validateString('treść', $postVars['comment'], 6, 512); $result = $comment->setComment($id, $text); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->put('/id/:id/status/:status', validatePrivileges(array('user', 'administrator')), function ($id, $status) use($app, $comment) { try { $c = $comment->getByID($id); if ($GLOBALS['privileges'] == 'user' && $status != 0) { throw new Exception('Jako użytkownik możesz jedynie zgłaszać nadużycia.', 403); } if ($GLOBALS['privileges'] == 'user' && $c['status_id'] > 1) { throw new Exception('Możesz zgłaszać nadużycia jedynie dla niezatwierdzonych komentarzy.', 403); }
function registerExe() { if (!validateEmail($_REQUEST['email'])) { addError("Email is wrong"); } $d = new Delegate(); $existingUser = $d->userGetByEmail(trim($_REQUEST['email'])); if (is_object($existingUser)) { addError("An user with same email already present."); } if (!validateString($_REQUEST['password'])) { addError("Password is not ok"); } if ($_REQUEST['password'] != $_REQUEST['password2']) { addError("Passwords do not match"); } if (!isset($_REQUEST['invitationToken'])) { if ($_REQUEST['captcha'] != $_SESSION['captcha']) { addError("Code was incorrect"); } } if (errors()) { redirect('../../register.php'); exit(0); } $user = new User(); $user->email = trim($_REQUEST['email']); $user->password = md5($_REQUEST['password']); $user->createdDate = now(); $user->lastLoginDate = now(); $user->lastLoginIp = $_SERVER['REMOTE_ADDR']; $user->lastBrowserType = $_SERVER['HTTP_USER_AGENT']; $userId = $d->userCreate($user); if (is_numeric($userId)) { addMessage("You were registered"); $_SESSION['userId'] = $userId; $_SESSION['captcha'] = null; unset($_SESSION['captcha']); //TODO: if we have a temp diagram we will redirect to save page if (isset($_SESSION['tempDiagram'])) { redirect('../saveDiagram.php'); } else { if (isset($_REQUEST['invitationToken'])) { $invitation = $d->invitationGetByToken($_REQUEST['invitationToken']); if (is_object($invitation)) { //find the diagram $diagram = $d->diagramGetById($invitation->diagramId); //create userdiagram $userdiagram = new Userdiagram(); $userdiagram->diagramId = $diagram->id; $userdiagram->invitedDate = $invitation->createdDate; $userdiagram->level = Userdiagram::LEVEL_EDITOR; $userdiagram->status = Userdiagram::STATUS_ACCEPTED; $userdiagram->userId = $userId; if (!$d->userdiagramCreate($userdiagram)) { addError("Could not add you to the diagram"); redirect('../editor.php'); exit; } //delete invitation $d->invitationDelete($invitation->id); //all is fine, redirect to the diagram redirect('../editor.php?diagramId=' . $diagram->id); } else { } redirect('../editor.php'); } else { redirect('../editor.php'); } } exit(0); } else { addError("User not added "); redirect('../../register.php'); exit(0); } }
$app->post('/id/:id/edit', validatePrivileges(array('user', 'administrator')), function ($id) use($app, $marker) { try { $m = $marker->getByID($id); if ($GLOBALS['privileges'] == 'user' && $GLOBALS['user_id'] != $m['user_id']) { throw new Exception('Nie jesteś autorem zgłoszenia.', 403); } $postVars = $app->request->post(); // Walidacja danych if (empty($postVars['type_id']) || empty($postVars['address']) || empty($postVars['description'])) { throw new Exception('Niekompletne dane.', 400); } if ($postVars['type_id'] < 0 || $postVars['type_id'] > 20) { throw new Exception('Zły format danych.', 400); } $address = validateString('adres', $postVars['address'], 4, 64); $description = validateString('opis', $postVars['description'], 6, 2048); $result = $marker->update($id, $postVars['type_id'], $address, $description); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->put('/id/:id/status/:status', validatePrivileges(array('user', 'administrator')), function ($id, $status) use($app, $marker) { try { $m = $marker->getByID($id); if ($GLOBALS['privileges'] == 'user' && $status != 0) { throw new Exception('Jako użytkownik możesz jedynie zgłaszać nadużycia.', 403); } if ($GLOBALS['privileges'] == 'user' && $m['status_id'] > 1) { throw new Exception('Możesz zgłaszać nadużycia jedynie dla niezweryfikowanych zgłoszeń.', 403); }
// Wysłanie e-maila z klucz aktywacyjnym if (mail($email, $subject, $message, $headers)) { $user->commit(); } else { throw new Exception('Nie można wysłać e-maila na podany adres.', 500); } jsonSuccess($app, $result); } catch (Exception $e) { $user->rollBack(); jsonError($app, $e); } }); $app->get('/lostpassword/:secret', function ($secret) use($app, $user) { try { // Walidacja danych $secret = validateString('klucz aktywacyjny', $secret, 64, 128); $u = $user->getBySecret($secret, 'administrator'); // Ostatnie 8 znaków jest losowym hasłem $password = substr(md5(time()), -8); $subject = 'Zmiana hasła'; $message = "Twój login to: {$u['login']}.\nTwoje nowe hasło to: {$password}."; $headers = 'From: admin@bariery.wroclaw.pl' . "\r\n" . 'Reply-To: no-reply@bariery.wroclaw.pl' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $user->beginTransaction(); $result = $user->change_lost_password($password, $secret); if (mail($u['email'], $subject, $message, $headers)) { $user->commit(); } else { throw new Exception('Nie można wysłać e-maila na adres użytkownika.'); } jsonSuccess($app, $result); } catch (Exception $e) {
function validateToken($token) { $token = str_replace('Token ', '', $token); $token = validateString('token', $token, 64, 128); return $token; }
function validateForm($username, $password1, $password2) { global $errors; global $password; if (validateRequired($username)) { if (!validateString($username)) { $errors['username'][] = 'Username needs to be String!'; } if (!validateAlphabethUsed($username)) { $errors['username'][] = 'Username needs to be in latin characters!'; } if (!validateLength($username, 5)) { $errors['username'][] = 'Username needs to be at least 5 characters long!'; } } else { $errors['username'][] = 'Username needs to be filled!'; } if (validateRequired($password1)) { if (!validateLength($password1, 5)) { $errors['password1'][] = 'Password needs to be at least 5 characters long!'; } if (!validatePassword($password1)) { $errors['password1'][] = "Password need to consist of one of the three of Capital, \nSmall letters, Digits and Special characters"; } } else { $errors['password1'][] = 'Password needs to be filled!'; } if (validateRequired($password2)) { if (!validateLength($password2, 5)) { $errors['password2'][] = 'Password needs to be at least 5 characters long!'; } if (!validatePassword($password2)) { $errors['password2'][] = "Password need to consist of one of the three of Capital, \nSmall letters, Digits and Special characters"; } if (validateRequired($password1)) { if (!validateMatchingPasswords($password1, $password2)) { $errors['password2'][] = "Password do not match!"; } else { $password = md5($password1); } } } else { $errors['password2'][] = 'Password needs to be filled!'; } }