How to generate 16 digit number with certain prefix - php

I'm trying to generate 16 digit number with a specific prefix. For example, the first four-digit should be 1800
1800485480692246
This is what I achieved so far
<?php
function generatenumber($limit){
$code = '';
for($i = 0; $i < $limit; $i++) {
$code .= mt_rand(0, 9);
}
return $code;
}
echo generatenumber(16);
?>

if you want a four-digit prefix then you should generate a 12 (16-4) digit number and append the prefix to it:
function generatenumber($limit, $prefix){
$code = '';
for($i = 0; $i < $limit; $i++) {
$code .= mt_rand(0, 9);
}
return $prefix.$code;
}
echo generatenumber(12, 1800); // 1800930423128799
Or just like #pistou mentioned, to keep the 16 as input:
function generatenumber($limit, $prefix){
$code = '';
if(strlen($prefix) > strlen($limit)) {
for($i = 0; $i < ($limit - strlen($prefix)); $i++) {
$code .= mt_rand(0, 9);
}
}
return $prefix.$code;
}
This approach would also allow to have a prefix in any length, without chaning the code:
echo generatenumber(16, 1800); // 1800930423128799
echo generatenumber(16, 12345678); // 1234567841559624
See the ouput here

Based on this answer, you could do as followed:
function generateNumber($limit=16, $prefix='') {
$digits = $limit - strlen($prefix);
$rand = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
return $prefix . $rand;
}
echo generateNumber(); // 0286940312944352
echo generateNumber(10); // 5532957240
echo generateNumber(16, 1800); // 1800045386499259

Related

Why can't I use a function to simplify my "for loops"

I build a webpage to crack simple MD5 hash of a four digit pin for fun. The method I used was basically try all combination and check against the MD5 value the user has entered. Below is the PHP code I created to accomplish the goal.
Debug Output:
<?php
$answer = "PIN not found";
if (isset($_GET['md5'])) {
$txt = 'abcdefjhig';
$time_pre = microtime(TRUE);
$value = $_GET['md5'];
$show = 15;
for ($i = 0; $i <= 9; $i++) {
$first = $i;
for ($j = 0; $j <= 9; $j++) {
$second = $j;
for ($k = 0; $k <= 9; $k++) {
$third = $k;
for ($x = 0; $x <= 9; $x++) {
$fourth = $x;
$whole = $first . $second . $third . $fourth;
$check = hash('md5', $whole);
if ($check == $value) {
$answer = $whole;
echo "The pin is $answer";
}
if ($show > 0) {
print"$check $whole \n";
$show = $show - 1;
}
}
}
}
}
echo "\n";
$time_post = microtime(TRUE);
print "Elapsed time:";
print $time_post - $time_pre;
}
?>
Notice that in the middle there are four very similar for loops,I tried to simplify this by using functions, but it just returns one four digit number which is 9999 instead of all of them.
Below is the function I created:
function construct($input){
for($i=0; $i<=9, $i++){
$input=$i;
}
return $input
}
Then I tried to call this function for four times to form all of the four digit numbers but it just gives me 9999. Can anybody help? Thanks a lot.
Try this:
for ($i=0; $i<=9999 ; $i++) {
$whole = sprintf('%04d', $i);
$check=hash('md5', $whole);
if($check==$value){
$answer=$whole;
echo "The pin is $answer";
break; //remove this if you do not want to break the loop here
}
if ($show>0) {
print"$check $whole \n";
$show=$show-1;
}
}
You're using numbers from 0 to 9999, so why just loop through those numbers? You can add zero's by using str_pad() like so:
for ($i = 0; $i <= 9999; $i++) {
$whole = str_pad($i, 4, '0', STR_PAD_LEFT);
}
Also I'd like to mention that you really should think about better formatting of your code, especially indentation

How to replace multiple random characters in string with underscore(_) in PHP

I am using codes like "gjhyYhK", "HJjhkeuJ" etc. But want user to show these codes like:
gj_y__K
HJj__e_J
means code will be edited with "_" at random positions in code.
This will do what you want:
$str = "gjhyYhK";
$len = strlen($str);
$num_to_remove = ceil($len * .4); // 40% removal
for($i = 0; $i < $num_to_remove; $i++)
{
$k = 0;
do
{
$k = rand(1, $len);
} while($str[$k-1] == "_");
$str[$k-1] = "_";
}
print $str . "\n";
If you want more underscores, change the value of $underscores. This will guarantee you get how many underscores you want, so long as you want fewer than the length of the string
Try this:
$string=array(
'gjhyYhK',
'HJjhkeuJ'
);
$arr=array();
foreach ($string as $key=>$value) {
$arr[$key]='';
for ($i=1; $i <=strlen($value); $i++) {
if(rand(0,1)){
$arr[$key].=substr($string[$key],$i,1);
}else{
$arr[$key].='_';
}
}
}
var_dump($arr);
you can try below code to get the functionality what you are looking for
<?php
$string = "gjhyYhK";
$percentage = 40;
$total_length = strlen($string);
$number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well
for ($i = 1; $i <= $number_of_underscore; $i++)
{
$random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced
if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_)
{
$string = preg_replace("/" . (substr($string, $random_position, 1)) . "/", '_', $string, 1); // here preg_replaced use to replace the character only once, (i.e str_replace() will replace all matching characters)
}
else
{
$i--; // else decrement $i for the loop to run one more time
}
}
echo $string;
?>
let me know if any other help needed
$str = "ADFJ";
$strlen = strlen($str);
$newStr = '';
for ($i = 0; $i < $strlen; $i++) {
if ($i == rand(0, $strlen)) {
$newStr .= '_';
} else {
$newStr .= $str[$i];
}
}
echo $newStr;

prevent Random PHP generator from including zeros

I have a php script that creates a random 10 digit order number:
// Assign order number length
$digits = 10;
// Create random order number to be stored with this order
$order_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
How do I prevent this from ever including the digit zero 0 in the random 10 digit number? Thanks in advance!
You can do fancy base conversions, but in the end, the most straightforward way is to just get a string:
function random_string($count, $available) {
$result = '';
$max = strlen($available) - 1;
for($i = 0; $i < $count; $i++) {
$result .= $available[rand(0, $max)];
}
return $result;
}
…
$order_number = random_string($digits, '123456789');
You can treat it as a number of base 9
base_convert(rand(0, pow(9, $digits) - 1), 10, 9)
This will give you numbers with digits from 0 to 8.
Now just add 1 to every digit to make it 1 to 9
(pow(10, $digits) - 1) / 9
will give you a number filled with ones. Now just add it to your previous number and there you go:
$digits = 10;
$order_number = (pow(10, $digits) - 1) / 9 + base_convert(rand(0, pow(9, $digits) - 1), 10, 9);
Try this :D
function getRandom($from, $to){
$num = rand($from, $to);
$have_zero = true;
$strNum = strval($num);
while ($have_zero){
$have_zero = false;
for ($i = 0; $i < sizeof($strNum); $i++){
if ($strNum[$i] == '0'){
$have_zero = true;
$num = rand($from, $to);
$strNum = strval($num);
break;
}
}
}
return $num;
}
getRandom(1111111111, 9999999999);
You could use a simple function like this:
function getRandom($length) {
$numbers = '';
for($i = 0; $i < $length; $i++) {
$numbers .= rand(1, 9);
}
return $numbers;
}
echo getRandom(10);
I would make a function.
<?php
function myRandomNumberWithoutZeros($digits)
{
$result = str_replace("0", "",rand(pow(10,$digits-1), pow(10, $digits)-1)."");
$resultLength = strlen($result);
if($resultLength < $digits)
{
return intval($result.myRandomNumberWithoutZeros($digits-$resultLength));
}
return intval($result);
}
echo myRandomNumberWithoutZeros(10);
?>

Auto incrementing unique url

I am looking to create an auto incrementing unique string using PHP, containing [a-Z 0-9] starting at 2 chars long and growing when needed.
This is for a url shrinker so each string (or alias) will be saved in the database attached to a url.
Any insight would be greatly appreciated!
Note this solution won't produce uppercase letters.
Use base_convert() to convert to base 36, which will use [a-z0-9].
<?php
// outputs a, b, c, ..., 2o, 2p, 2q
for ($i = 10; $i < 99; ++$i)
echo base_convert($i, 10, 36), "\n";
Given the last used number, you can convert it back to an integer with intval() increment it and convert the result back to base 36 with base_convert().
<?php
$value = 'bc9z';
$value = intval($value, 36);
++$value;
$value = base_convert($value, 10, 36);
echo $value; // bca0
// or
echo $value = base_convert(intval($value, 36) + 1, 10, 36);
Here's an implementation of an incr function which takes a string containing characters [0-9a-zA-Z] and increments it, pushing a 0 onto the front if required using the 'carry-the-one' method.
<?php
function incr($num) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$parts = str_split((string)$num);
$carry = 1;
for ($i = count($parts) - 1; $i >= 0 && $carry; --$i) {
$value = strpos($chars, $parts[$i]) + 1;
if ($value >= strlen($chars)) {
$value = 0;
$carry = 1;
} else {
$carry = 0;
}
$parts[$i] = $chars[$value];
}
if ($carry)
array_unshift($parts, $chars[0]);
return implode($parts);
}
$num = '0';
for ($i = 0; $i < 1000; ++$i) {
echo $num = incr($num), "\n";
}
If your string was single case rather than mixed, and didn't contain numerics, then you could literally just increment it:
$testString="AA";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
$testString="aa";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
But you could possibly make some use of this feature even with a mixed alphanumeric string
To expand on meagar's answer, here is how you can do it with uppercase letters as well and for number arbitrarily big (requires the bcmath extension, but you could as well use gmp or the bigintegers pear package):
function base10ToBase62($number) {
static $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$result = "";
$n = $number;
do {
$remainder = bcmod($n, 62);
$n = bcdiv($n, 62);
$result = $chars[$remainder] . $result;
} while ($n > 0);
return $result;
}
for ($i = 10; $i < 99; ++$i) {
echo base10ToBase62((string) $i), "\n";
}

PHP Random Number

I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.

Categories