I am new to PHP and want to generate unique 10 digits number for my SKU Number. I tried using a date with IP address and got a unique value first time. But after a refresh or saving product data I still have that same SKU number. Any Help?? My code is:
<?php
if(!empty($_POST)) {
.....my code......
}
else{
$stamp = date("Ymdhis");
$ip = $_SERVER['REMOTE_ADDR'];
$sku = "$stamp-$ip";
$sku = str_replace(".", "", "$sku");
$sku = str_replace("-", "", "$sku");
$sku = str_replace(":", "", "$sku");
$sku = substr($sku, 0,10);
}
?>
Here's a quick random-string-generator I wrote:
function generateRandomString($alpha = true, $nums = true, $usetime = false, $string = '', $length = 120) {
$alpha = ($alpha == true) ? 'abcdefghijklmnopqrstuvwxyz' : '';
$nums = ($nums == true) ? '1234567890' : '';
if ($alpha == true || $nums == true || !empty($string)) {
if ($alpha == true) {
$alpha = $alpha;
$alpha .= strtoupper($alpha);
}
}
$randomstring = '';
$totallength = $length;
for ($na = 0; $na < $totallength; $na++) {
$var = (bool)rand(0,1);
if ($var == 1 && $alpha == true) {
$randomstring .= $alpha[(rand() % mb_strlen($alpha))];
} else {
$randomstring .= $nums[(rand() % mb_strlen($nums))];
}
}
if ($usetime == true) {
$randomstring = $randomstring.time();
}
return($randomstring);
} // end generateRandomString
You can use it like this for what you need:
$SKU = generateRandomString(false, true, false, '', 10);
you could use this $sku = rand(1000000000,9999999999)
this php function will generate a random no. every time
Why not use the date to create a 10 digit unique number? year (4) + month with leading zero (2) + day with leading zero (2) + seconds with leading zero (2) = 10 digits
<?php
echo date("Ymds");
?>
Yall overcomplicating.
Use an existing library like random_compat (This library can generate strong random numbers and cryptographically secure random numbers.). https://github.com/ircmaxell/random_compat/blob/master/lib/random.php
Example (your case):
$random = new \PHP\Random(true);
echo $random->token(10, '0123456789');