Created
August 26, 2025 15:18
-
-
Save mehrshaddarzi/e9e27a76de36c019c2c8884910742c08 to your computer and use it in GitHub Desktop.
Generate unique Random Number in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function generate_secure_unique_number($order_id, $digits = 24) { | |
| $salts = array(); | |
| $salt_constants = array( | |
| 'AUTH_KEY', | |
| 'SECURE_AUTH_KEY', | |
| 'LOGGED_IN_KEY', | |
| 'NONCE_KEY', | |
| 'AUTH_SALT', | |
| 'SECURE_AUTH_SALT', | |
| 'LOGGED_IN_SALT', | |
| 'NONCE_SALT' | |
| ); | |
| foreach ($salt_constants as $constant) { | |
| if (defined($constant)) { | |
| $salts[] = constant($constant); | |
| } | |
| } | |
| // اگر هیچ saltی پیدا نشد، از یک مقدار پیشفرض استفاده کنیم | |
| if (empty($salts)) { | |
| $salts[] = 'fallback_secret_key_' . DB_PASSWORD; | |
| } | |
| // دریافت نام دامنه | |
| $domain = get_site_url(); | |
| // دریافت timestamp با دقت میکروثانیه | |
| $microtime = microtime(true); | |
| // ترکیب تمام saltها | |
| $combined_salt = implode('', $salts); | |
| // ایجاد یک رشته ترکیبی | |
| $combined_string = $order_id . $domain . $microtime . $combined_salt . uniqid('', true); | |
| // تولید هش | |
| $hash = hash('sha512', $combined_string); | |
| // تبدیل به عدد | |
| $numeric_hash = ''; | |
| for ($i = 0; $i < strlen($hash); $i += 2) { | |
| $hex_pair = substr($hash, $i, 2); | |
| $numeric_hash .= hexdec($hex_pair); | |
| } | |
| // محدود کردن به تعداد ارقام مورد نظر | |
| $unique_number = substr($numeric_hash, 0, $digits); | |
| // اگر تعداد ارقام کافی نبود، تکمیل کنیم | |
| if (strlen($unique_number) < $digits) { | |
| $additional_hash = hash('sha256', $unique_number . microtime() . $combined_salt); | |
| $additional_numeric = preg_replace('/[^0-9]/', '', $additional_hash); | |
| $unique_number .= substr($additional_numeric, 0, $digits - strlen($unique_number)); | |
| } | |
| // اگر باز هم با صفر شروع شد (که بسیار نادر است)، اولین رقم را تغییر دهیم | |
| if (substr($unique_number, 0, 1) === '0') { | |
| $first_digit = rand(1, 9); | |
| $unique_number = $first_digit . substr($unique_number, 1, $digits - 1); | |
| } | |
| // اطمینان از طول دقیق | |
| return str_pad($unique_number, $digits, '0', STR_PAD_RIGHT); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment