function randomstring($length) { /*$c = "abcdefghijklmnopqrstuvwxyz"; $rand = ''; srand((double)microtime()*1000000); for ($i=0; $i<$length; $i++) { $rand .= $c[rand()%strlen($c)]; } return $rand;*/ $random = GeneratePassword(false, $length, "/^[a-z]{1}[a-z0-9]*\$/"); $return = implode('', $random); return $return; }
if ($_GET["passworderror"] == "true") { echo "please enter password"; } } if (isset($_GET["emailempty"])) { if ($_GET["emailempty"] == "true") { echo "please enter email"; } } if (isset($_GET["emailnotvalid"])) { if ($_GET["emailnotvalid"] == "true") { echo "email not valid"; } } $length = 8; $password = GeneratePassword(8); function GeneratePassword($length) { $password = ""; for ($i = 0; $i < $length; $i++) { $ascii = rand(65, 90); $password .= chr($ascii); } return $password; } ?> <!DOCTYPE html> <html lang="en"> <head>
$changepasswordsessionid = mmb_validate($_REQUEST, 'changepasswordsessionid', ''); if (empty($changepasswordsessionid)) { $action = ""; return; } $sql = "select user_id, user_email, user_name from Users where user_sessionfornewpassword = trim('{$changepasswordsessionid}')"; // echo $sql; $Row = CSql::singleRow($sql); $UserId = $Row['user_id']; $UserEmail = $Row['user_email']; $UserName = $Row['user_name']; // echo $UserEmail; // Если идентификаторы совпали - меняем пароль // Возможно здесь стоит сразу стартовать сессию... if ($UserId > 0) { $NewPassword = GeneratePassword(6); // пишем в базу пароль и время отправки письма с паролем // обнуляем сессию для восстановления и её время $sql = "update Users set user_password = '******',\n\t\t user_sendnewpassworddt = now(),\n\t\t\t\t\t user_sessionfornewpassword = null,\n\t\t\t\t\t user_sendnewpasswordrequestdt = null\n\t\t where user_id = {$UserId}"; // echo $sql; $rs = MySqlQuery($sql); $Msg = "Уважаемый пользователь {$UserName}!\r\n\r\n"; $Msg .= "Согласно подтверждённому запросу с Вашего адреса e-mail,\r\n"; $Msg .= "для Вашей учетной записи на сайте ММБ создан пароль: {$NewPassword}\r\n"; // Отправляем письмо SendMail(trim($UserEmail), $Msg, $UserName); CMmb::setShortResult("Пароль {$NewPassword} выслан.", 'MainPage'); // и вот тут м.б. стоит активировать сессию, чтобы автоматом войти на сайт $SessionId = StartSession($UserId); } $changepasswordsessionid = "";
function ResetPassword($user_id) { global $db; $result = $db->Query("SELECT `username`, `email` FROM `bayonet_users` WHERE `user_id` = '{$user_id}' LIMIT 1"); $admin = $db->FetchRow($result); decho($admin); if (isset($_POST['proceed'])) { $password = GeneratePassword(8); $cryptpassword = crypt(md5($password), 'iamnotadirtywhorebitch'); $status = EmailPassword($admin['username'], $password, $admin['email']); if ($status) { $db->Query("UPDATE `bayonet_users` SET `password` = '{$cryptpassword}' WHERE `user_id` = '{$user_id}' LIMIT 1"); echo "Password has been reset and emailed to '{$admin['username']}'"; PageRedirect(3, "?op=admins"); } else { ReportError("An error has occured emailing the new password. It will not take effect."); } return; } if (isset($_POST['cancel'])) { echo "The password <b>WILL NOT</b> be reset for '{$admin['username']}'"; PageRedirect(3, "?op=admins"); return; } ?> <center> <form action="<?php $_SERVER['PHP_SELF']; ?> " method="post"> <table> <th>Are you SURE you want to reset this user's password: '******'username']; ?> '?</th> <tr><th><button name="proceed">Yes</button> <button name="cancel">No</button></th></tr> </table> </form> </center> <?php }
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $password = ""; for ($i = 0; $i < $password_length; $i++) { $password .= $chars[rand(0, strlen($chars) - 1)]; } return $password; } // ================================================== // Initialise variables for the operation. // ================================================== $gid = $_POST["gid"]; $time = $current_time; $expiry = $current_time + $SESSION_TIMEOUT; $owner = $_SERVER["REMOTE_ADDR"]; $sid = $_POST["sid"]; $pass = GeneratePassword(); $ip = $_SERVER["REMOTE_ADDR"]; $port = 0; $state = $STATUS_ACTIVE; $title = $_POST["title"]; $tslots = $_POST["tslots"]; $uslots = $_POST["uslots"]; $players = ""; $info = $_POST["info"]; // ================================================== // Verify all input data. // ================================================== // Verify that the session id is valid. // Verify that the title is valid. // Verify that the slots are valid. // Verify that the info is valid.
<?php if ($Module == 'register' and $_POST['registration']) { $_POST['E-mail'] = FormChars($_POST['E-mail']); $_POST['password'] = GeneratePassword($_POST['password'], $_POST['E-mail']); $_POST['captcha'] = FormChars($_POST['captcha']); if (!$_POST['E-mail']) { MessageSend(1, 'Введи E-mail'); } echo $_POST['E-mail'] . ' ' . $_POST['password']; }
$sql .= "CMS_USER_NAME, "; $sql .= "CMS_USER_EMAIL "; $sql .= "FROM CMS_USER "; $sql .= "WHERE "; $sql .= "CMS_USER_LOGIN='******' AND "; $sql .= "CMS_USER_EMAIL='" . $db->real_eacape_string($email) . "' AND "; $sql .= "CMS_USER_STATUS='1' AND "; $sql .= "CMS_USER_ACTIVEDATE <= NOW() AND "; $sql .= "(CMS_USER_EXPIRYDATE IS NULL OR CMS_USER_EXPIRYDATE >= NOW()) "; $db = connectDB(); $sql = sprintf("SELECT ID, CMS_USER_NAME, CMS_USER_EMAIL FROM CMS_USER WHERE CMS_USER_LOGIN='******' AND CMS_USER_EMAIL='%s' AND CMS_USER_STATUS = 1 AND CMS_USER_ACTIVEDATE <= NOW() AND (CMS_USER_EXPIRYDATE IS NULL OR CMS_USER_EXPIRYDATE >= NOW())", $db->real_escape_string($name), $db->real_escape_string($email)); $result = $db->query($sql) or die($sql); // Check user existed if ($result->num_rows > 0) { $row = $result->fetch_array(); // Reset password $newPassword = GeneratePassword(); // Send new password to the email SendForgotPasswordEmail($row["CMS_USER_EMAIL"], $row["CMS_USER_NAME"], $newPassword); // Update table $sql = "UPDATE CMS_USER SET CMS_USER_PASS = MD5('" . $newPassword . "') WHERE ID = " . $row["ID"]; $db->query($sql); // Return sucess notification $responseStatus = 1; } else { $responseStatus = -1; $responseMsg = CONST_ERROR_MESSAGE_NONEXISTED_USERNAME_OR_EMAIL; } } // Echo result echo json_encode(array("status" => $responseStatus, "responseMsg" => $responseMsg));
<?php $input = "0123456789abcdefghijklmnopqrstuvwxyz"; $count = 8; echo GeneratePassword($input, $count); function GeneratePassword($chars, $len) { $charsLen = strlen($chars) - 1; //echo $charsLen; str_shuffle($chars); //打乱字符串 $output = ''; for ($i = 0; $i < $len; $i++) { $output .= $chars[mt_rand(0, $charsLen)]; } return $output; } echo "<br/>"; $arr = array("ffffffff", "sdfsfsd", "fdsfsfsdfsfds", "fdsdfdssfsdfsfsdfds"); echo GetLongestString($arr); function GetLongestString($arrayString) { $i = 0; foreach ($arrayString as $str) { if (strlen($str) > $i) { $i = strlen($str); } } return $i; } echo "<br/>";
return null; $ret = str_shuffle($str); while (strlen($ret) < $len) { $ret = $ret . str_shuffle($str); } return $ret; */ return substr(str_shuffle(str_pad($str, $len, $str)), 0, $len); } echo "<h4>GeneratePassword</h4>"; echo GeneratePassword(-5, "abc") . "<br />"; echo GeneratePassword(0, "abc") . "<br />"; echo GeneratePassword(2, "") . "<br />"; echo GeneratePassword(1, null) . "<br />"; echo GeneratePassword(3, "abac") . "<br />"; echo GeneratePassword(6, "abac") . "<br />"; echo GeneratePassword(4, "abac") . "<br />"; function GetLongestString() { return max(array_map("strlen", func_get_args())); } echo "<h4>GetLongestString</h4>"; echo GetLongestString("abc", "a", "abcde", "abcd") . "<br />"; echo GetLongestString() . "<br />"; echo GetLongestString("") . "<br />"; $time_start = microtime_float(); for ($i = 0; $i < 100000; $i++) { GetLongestString("abc", "a", "abcde", "abcd", "abc", "saea", "abcddfse", "absdcd", "abcasdfgasdgasasd", "sadfa", "abcdsdgdge", "abgsdfscd"); } echo microtime_float() - $time_start;