- 12 способов для генерации пароля на PHP
- Вариант 1.
- Вариант 2.
- Вариант 3.
- Вариант 4.
- Вариант 5.
- Вариант 6.
- Вариант 7.
- Вариант 8.
- Вариант 9.
- Вариант 10.
- Вариант 11.
- Вариант 12.
- How to Create Forgot System Password with PHP & MySQL
- Create Forgot System Password
- How to Create MySQL Database Table
- How to Create User Login Form
- How to Implement User Login
- How to Create Forget Password Form
- How to Implement Password Forgot Functionality
- How to Create Password Forgot Form
- Forgot System Password Form
- How to Save New Password
- Download Complete Source Code
12 способов для генерации пароля на PHP
Рано или поздно при создании паролей нам приходится пользоваться функциями для случайного создания паролей. На этот раз хотелось бы поделиться различными способами генерации паролей на языке PHP.
Я не являюсь автором данных функций и всего лишь попытался собрать наиболее интересные варианты с моей точки зрения. И так, давайте же рассмотрим их.
Вариант 1.
/** * Generate password * * @param int $length * @return string */ function generatePassword001(int $length = 8): string < $password = ''; for ($i = 0; $i < $length; $i++) < $password .= chr(rand(32, 126)); >return $password; >
Вариант 2.
/** * Generate password * * @param int $length * @return string */ function generatePassword002(int $length = 8): string < $password = ''; $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $limit = strlen($characters) - 1; for ($i = 0; $i < $length; $i++) < $password .= $characters[rand(0, $limit)]; >return $password; >
Вариант 3.
/** * Generate password * * @param int $length * @return string */ function generatePassword003(int $length = 8): string
Вариант 4.
/** * Generate password * * @param int $length * @return string */ function generatePassword004(int $length = 8): string < $password = openssl_random_pseudo_bytes(ceil($length * 0.67), $crypto_strong); $password = str_replace(['=', '/', '+'], '', base64_encode($password)); $password = substr($password, 0, $length); return $password; >
Вариант 5.
/** * Generate password * * @param int $length * @return string */ function generatePassword005(int $length = 8): string < try < $password = str_replace(['=', '/', '+'], '', base64_encode(random_bytes($length))); $password = substr($password, 0, $length); return $password; >catch (Exception $e) < return $e->getMessage(); > >
Вариант 6.
/** * Generate password * * @param int $upper * @param int $lower * @param int $numeric * @param int $other * @return string */ function generatePassword006($upper = 2, $lower = 3, $numeric = 2, $other = 1): string < $password = ''; $passwordOrder = []; for ($i = 0; $i < $upper; $i++) < $passwordOrder[] = chr(rand(65, 90)); >for ($i = 0; $i < $lower; $i++) < $passwordOrder[] = chr(rand(97, 122)); >for ($i = 0; $i < $numeric; $i++) < $passwordOrder[] = chr(rand(48, 57)); >for ($i = 0; $i < $other; $i++) < $passwordOrder[] = chr(rand(33, 47)); >shuffle($passwordOrder); foreach ($passwordOrder as $char) < $password .= $char; >return $password; >
Вариант 7.
/** * Generate password * * @param int $length * @param string $availableSets * @return string */ function generatePassword007(int $length = 8, string $availableSets = 'luds'): string < $symbols = []; $password = ''; $str = ''; if (strpos($availableSets, 'l') !== false) < $symbols[] = 'abcdefghjkmnpqrstuvwxyz'; >if (strpos($availableSets, 'u') !== false) < $symbols[] = 'ABCDEFGHJKMNPQRSTUVWXYZ'; >if (strpos($availableSets, 'd') !== false) < $symbols[] = '23456789'; >if (strpos($availableSets, 's') !== false) < $symbols[] = '!@#$%&*?'; >foreach ($symbols as $symbol) < $password .= $symbol[array_rand(str_split($symbol))]; $str .= $symbol; >$str = str_split($str); for ($i = 0; $i < $length - count($symbols); $i++) < $password .= $str[array_rand($str)]; >$password = str_shuffle($password); return $password; >
Вариант 8.
/** * Generate password * * @param int $length * @return string */ function generatePassword008(int $length = 8): string < $password = ''; $possible = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $i = 0; $lenPossible = strlen($possible) - 1; while ($i < $length) < $char = substr($possible, mt_rand(0, $lenPossible), 1); if (!strstr($password, $char)) < $password .= $char; $i++; >> return $password; >
Вариант 9.
/** * Generate password * * @param int $length * @return string */ function generatePassword009(int $length = 8): string < $password = substr(str_shuffle(strtolower(sha1(rand() . time() . 'here our salt'))), 0, $length); for ($i=0, $c = $length; $i < $c; $i++) < $password[$i] = rand(0, 100) >50? strtoupper($password[$i]):$password[$i]; > return $password; >
Вариант 10.
/** * Generate password * * @param int $length * @return false|string * @throws Exception */ function generatePassword010(int $length = 8): string < if (function_exists('random_bytes')) < try < $bytes = random_bytes(ceil($length / 2)); >catch (Exception $e) < return $e->getMessage(); > > elseif (function_exists('openssl_random_pseudo_bytes')) < $bytes = openssl_random_pseudo_bytes(ceil($length / 2)); >else < throw new Exception("no cryptographically secure random function available"); >$password = substr(bin2hex($bytes), 0, $length); for ($i=0, $c = $length; $i < $c; $i++) < $password[$i] = rand(0, 100) >50? strtoupper($password[$i]):$password[$i]; > return $password; >
Вариант 11.
/** * Generate password * * @param int $numAlpha * @param int $numDigit * @param int $numNonAlpha * @return string */ function generatePassword011($numAlpha = 4, $numDigit = 2, $numNonAlpha = 2): string < $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $listDigits = '0123456789'; $listNonAlpha = ',;. $/*-+&@_+;./*&?$-!,'; return str_shuffle( substr(str_shuffle($listAlpha), 0, $numAlpha) . substr(str_shuffle($listDigits), 0, $numDigit) . substr(str_shuffle($listNonAlpha), 0, $numNonAlpha) ); >
И еще один последний вариант генерации пароля от меня. Данный вариант похож на 7й, но с небольшими изменениями и добавлением еще вариантов с кириллицей.
Вариант 12.
/** * Generate password * - * @param int $length * @param string $availableSets * @return string */ function generatePassword012(int $length = 8, string $availableSets = 'luds'): string < $symbols = []; $password = $str = $oldIdx = ''; $availableSets = str_split($availableSets); if (in_array('l', $availableSets)) < // Letters lower $symbols[] = 'abcdefghjkmnpqrstuvwxyz'; >if (in_array('u', $availableSets)) < // Letters upper $symbols[] = 'ABCDEFGHJKMNPQRSTUVWXYZ'; >if (in_array('d', $availableSets)) < // Digits $symbols[] = '23456789'; >if (in_array('s', $availableSets)) < // Special symbols $symbols[] = '!@#$%&*?'; >if (in_array(1, $availableSets)) < // Russian Letters lower $symbols[] = 'абвгдеёжзийклмнпрстуфхцчшщыэюяъь'; >if (in_array(2, $availableSets)) < // Russian Letters lower $symbols[] = 'АБВГДЕЁЖЗИЙКЛМНПРСТУФХЦШЩЫЭЮЯЪЬ'; >$symbols = implode('', $symbols); $symbols = preg_split('//u', $symbols, null, PREG_SPLIT_NO_EMPTY); for ($i=0; $i < $length; $i++) < do < $newIdx = array_rand($symbols); >while($newIdx == $oldIdx); $password .= $symbols[$newIdx]; $oldIdx = $newIdx; > return $password; >
Естественно, здесь перечислены не все возможные способы, а наиболее понравившиеся мне. Возможно, вы используете более интересные решения. Всегда готов выслушать все ваши комментарии. А еще вы можете сгенерировать пароль на данном сайте.
Спасибо и до новых встреч.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
How to Create Forgot System Password with PHP & MySQL
Forgot System Password is a web application feature to allow users to Forgot their password if they forget their password. To save your new password with password Forgot username email id is allowed with username or email address to send password forgot link.
So if you are thinking about implementing Forgot System Password with PHP in your application, then it is discussed here at the right place. This tutorial will learn how to apply Forgot System Password or forget the password functionality using PHP and MySQL. You can also develop complete user management systems with PHP and MySQL to manage users.
Create Forgot System Password
We will cover this tutorial step by step with the live demo. You will also be able to download the full source code of the live demo.
So now we will start to implementing Forgot System Password with PHP and MySQL. Before we begin, take a look on files structure for this example.
How to Create MySQL Database Table
In this tutorial, we will try to create live example for password forget functionality. So we will create MySQL database table members for user login details.
CREATE TABLE `members` ( `id` int(11) NOT NULL, `username` varchar(250) NOT NULL, `email` varchar(250) NOT NULL, `password` varchar(250) NOT NULL, `authtoken` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We will insert user records into members table for Forgot System Password functionality.
INSERT INTO `members` (`id`, `username`, `email`, `password`, `authtoken`) VALUES (1, 'test', 'test@webdamn.com', '827ccb0eea8a706c4c34a16891f84e7b', '91e8cc3c6bc400c70fd17c3836e01287');
How to Create User Login Form
First we will create user login form in index.php with forget password link.
How to Implement User Login
We will implement user login functionality by handling user login form submit in user.js. We will make ajax request to action.php to handle user login and get JSON response.
$('#loginForm').on('submit', function(e) $.ajax( type: 'POST', url : "action.php", data: $(this).serialize(), dataType: "json", success: function (response) if(response.success == 1) location.href = "https://webdamn.com/index.php"; else $('#errorMessge').text(response.message); $('#errorMessge').removeClass('hidden'); ); return false; );
In action.php, we will call method $user->login() to implement user login functionality.
login(); if($userDetails) $message = "Logged in successfully"; $status = 1; else $message = "Invalid Email/Password"; $status = 0; $jsonResponse = array ( "message" => $message, "success" => $status ); echo json_encode($jsonResponse); ?>
In class User.php, we will define method login().
public function login() $sqlQuery = " SELECT * FROM ".$this->memberTable." WHERE email='".$_POST['userEmail']."' AND password='".md5($_POST['userPassword'])."'"; return $this->getData($sqlQuery);
How to Create Forget Password Form
If user forget password, then user can Forgot their password by clicking Forget Password link on login form. The forget password form created in forget_password.php to Forgot form using username or email address.
How to Implement Password Forgot Functionality
Now we will implement Forgot System Password functionality by making ajax request to action.php.
$('#forgetForm').on('submit', function(e) $.ajax( type: 'POST', url : "action.php", data: $(this).serialize(), dataType: "json", success: function (response) if(response.success == 2) $('#errorMessge').text(response.message); $('#errorMessge').removeClass('hidden alert-success').addClass('alert-danger'); else if(response.success == 1) $('#inputSection').addClass('hidden'); $('#errorMessge').text(response.message); $('#errorMessge').removeClass('hidden alert-danger').addClass('alert-success'); else if(response.success == 0) $('#errorMessge').text(response.message); $('#errorMessge').removeClass('hidden alert-success').addClass('alert-danger'); ); return false; );
In action.php, we will call method $user->forgotPassword() from User.php class and return JSON response.
if(!empty($_POST['action']) && $_POST['action'] == 'forgetPassword') if($_POST['userEmail'] == '' && $_POST['userName'] == '') $message = "Please enter username or email to proceed with password forgot"; $status = 2; else $userDetails = $user->forgotPassword(); if($userDetails) $message = "Forgot System Password link send. Please check your mailbox to Forgot password."; $status = 1; else $message = "No account exist with entered username and email address."; $status = 0; $jsonResponse = array ( "message" => $message, "success" => $status ); echo json_encode($jsonResponse);
In class User.php, we can define method ForgotPassword(). In this method, we will check for user account by username or email. If user account exist then we will create Forgot System Password link with authtoken and send password Forgot email to user email address.
public function forgotPassword() $sqlQuery = " SELECT email FROM ".$this->memberTable." WHERE email='".$_POST['userEmail']."' OR username='".$_POST['userName']."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $numRows = mysqli_num_rows($result); if($numRows) while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) $link="forgot Password"; $to = $row['email']; $subject = "forgot your password on examplesite.com"; $msg = "Hi there, click on this ".$link." to forgot your password."; $msg = wordwrap($msg,70); $headers = "From: info@webdamn.com"; mail($to, $subject, $msg, $headers); return 1; else return 0;
How to Create Password Forgot Form
When user click password forgot link, then the user password forgot form displayed to save new password. So we will create new password save form in forgot_password.php.
" />Forgot System Password Form