Generating 'word of the day' via PHP Random Number - php

I'm stuck with a small issue and don't want to generate my own algo for random number.
I've to Display 'word of the day' on website, it has to change only once per day and all data is stored in XML. At pageload I read xml file by simpleXml Parser in php and then generate a random number between 0, length of array and output a term + definition.
But i dont want it to change with every refresh, nor do I want to save it on server in database.
So how can I generate a random number between 0 to N, which would give same value for a span of 24 hours.

Just set the current date as Seed without hours, minutes and seconds.
srand(mktime(0, 0, 0));
$wordIndex = rand(0, $wordCount);
It will return the same number for one Day.

Option 1: No random numbers, just increase the index by one every day. It will look random enough since no one knows your file. If that is not good enough, randomize the input file (shuffle it once and safe it out again).
Option 2: Use today's date as the seed for the random number generator.

<?
srand(date("ymd"));
echo rand();
?>

If you dont want to store it, then use something, that is connected to daily cycle, for example, the date, or weekday.

Related

How to generate unique auto increment value for each user in laravel and add it to database

I am developing a event organization website. Here when the user registers for an event he will be given a unique random number(10 digit), which we use to generate a barcode and mail it to him. Now,
I want to make the number unique for each registered event.
And also auto increment
One solution is to grab all the auto increment numbers in an array and generate a auto increment number using laravel takes the form (0000000001 to 9999999999) and loop through and check all the values. Grab the first value that doesn't equal to any of the values in the array and add it to the database.
But I am thinking that there might be a better solution to this. Any suggestion?
Select Maximum number stored in your DB and add 1 in it like:
SELECT (MAX(Column_Name)+1) AS Max_val FROM Table_Name;
I suggest simple timestamp-based solution using the Carbon class to produce a unique number using timestamp. It's fairly simple to have a basic unique and random stamp generation using timestamp.
You can use as given below,
use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like this 1552296328
You can use it as a unique identifier. If you want the next numbers, just +1. But keep in mind, you have to manage another number batch in a timely manner. (i.e if you have generated 500 numbers for now by increment, You should not generate another number for the next 500 seconds. Otherwise, it will repeat the number). If you want to know more, you can read here.
The solution with rand() function may not work here because it can re-produce the existing number in the database and you will be errored for Unique Constraint Violation(i.e. If you have column unique in DB).
No matter what approach you use, it would never be truly random. It will be PRNG. For your case, I think auto increment with zero fill should be enough.
But if you are set on using random number then using rand() function of PHP should be enough. 10 digit means 10000000000 unique number.Unless your project has millions of events it should realistically be no problem. So, approach 1 should be no problem. Also, you can check after generating any random number that whether that number is already present(There is 0.000001% or something like that chance.). If it is present then try to generate a random number again.
But if your project gets very successful (I.E. millions of events) then problems similar to Y2K might creep up.
MySQL UUID would give you truly unique is: Store UUID v4 in MySQL
You don’t need to worry about auto incrementing.

What is the max number mt_rand() can generate in windows?

Actually in my php application i want to assign every user a unique number code. For that i am using mt_rand(0,100000000). I want it to generate millions of number for say millions of different users without repeats and save it to database. Is it possible ? Or any other technique is recommended ?
Also to make sure the number doesn't repeat I am checking if the number already exists in the db through php, if it does exist i reload the page to generate another number and save it to db orelse continue to save the number as it is.
Is it the best pratice ?
I am new to this non repeating number generator in php so don't know the efficient method.
You can use mt_getrandmax() to get the biggest value for mt_rand().
Just as the doc says,
max: Optional highest value to be returned (default: mt_getrandmax())
min max range must be within the range mt_getrandmax(). i.e. (max - min) <= mt_getrandmax() Otherwise, mt_rand() may return poorer random numbers than it should.

php set daily number in range for each ID

I'm trying to calculate a sort or "daily random number" in a range, wich can't be guessed, for each user in our site but can't figure out how to do it.
I don't want a random number either, it must be a calculated number in PHP, not an additional database field or anything similar.
I tought at a function who can take the user's ID and the day of year and calculate this number.
Example:
USERID: 12345, Range: 0-7 (constant values for every user)
DayOfYear: 250 (change every day)
Then something like: ((12345 + 250) MODULO 8) (so I've range from 0 to 7 for each user). The problem is that the same number will come out every 8 days in a loop that user will find very fast.
Each user don't necessarly need a different number for every day, even the same number would be OK for a few days but not all users must have the same number. Also, most important, no loop scenario, so user can't guess his his daily number.
Thank you for your help.
There are so many answers to this question and none would be the best ... but I'm in a funny mood:
$id = hexdec(substr(md5($userId . date('z')), 0, 3)) % 8;
Use the md5-function to get a hex-string from a string. Then use a part of this string to calculate the mod 8.
For the next 10 days the id will be 5,7,5,3,6,0,2,0,2,4 when using your user id
But to guess a number between 0 and 7 isn't so hard, don't uses this for security ...

Generate random number that changes every month

I need to generate a random number within a given range. The number must be different for every new month of the year, and it should not be the same (although theoretically it is possible) as the number generated the year before for that given month.
I was thinking of using the php rand($min, $max) function in conjunction with date("w"), I am struggling with the part where I need to get different results for every year.
To illustrate what I mean, check this:
$numbers = range(1, 100); //our random array
echo $numbers[date("w")]; //date("w") returns number of week
There are 2 problems here: 1) it is not really random, 2) the number will be the same every year and 3) it does not reflect the whole size of the array as date("w") returns a number between 1 and 52.
Do you think this is accomplishable in pure PHP? Or do I need to make a cronjob for this?
Thank you for any help.
You could use every month the same number in the seed. Just to be clear the seed in the function srand ([ int $seed ] ).
You can do something like this:
srand(100);
echo rand();
and every time it returns the same number. So every month you can do something like this:
$min = 1;
$max = 100;
date_default_timezone_set('UTC');
$seed = date('Ym'); // it is the date as an integer
srand($seed);
echo rand($min, $max);
Pay attention to set the default time zone. If you don't, the result will depend to the server configuration.
-- UPDATE --
As #StevenSmith and #axiac stated you're not 100% sure the random generated number is unique.
In other words this means that wider the range (min-max) higher the probability you'll have every time a different number.
Use date('Ym') to generate an unique identifier for each (year, month) combination, use this value to initialize the pseudo-random generator's engine then generate one random number:
srand(date('Ym'));
$value = rand(1, 100);
Adjust the second line to match your needs. Now it generates an integer number between (and including) 1 and 100.
The value returned by date('Ym') is the same during a month. Every time you call srand() with a certain argument, the pseudo-random generator is reinitialized using that value and then it produces the same sequence of pseudo-random numbers when rand() is invoked (several times).
This ensures the generation of the same value for you during the entire month. During the next month and during the same month of the subsequent years the pseudo-random number generator is initialized with a different value and it generates a different sequence of pseudo-random numbers.
Depending on the values you use in your call to rand(), it might happen that the value returned by it this month is returned again in a different month. Use a large range for its $min and $max arguments to minimize this possibility.
You could generate a random number, select the closest multiple of 12, and then add the current month number.
For example, if the random number is 616, the closest multiple of 12 is 612. Add 0 (since it's currently January) giving you a final answer of 612. This will ensure that the number is unique for each month.

Generating a random number from date in a reproducive manner in PHP

I have been struggling with a problem for a while now.
Namely I need to generate a number in range 1 - 50 using a date. What I mean is if I run a some piece of code withing a specific date, it should produce me the same number for that day. If the date changes it should produce me a different number in defined range and preferably that does not show pattern with numbers generated in previous dates (constantly rising for example). I believe it can't be done with some mathematical linear function since the graph of that function would always produce me a pattern how the numbers are changing in time. Perhaps there is some function that is used in cryptography that would help?
seed your random generator via srand
If the input number should does not change for the day then your random returns will be predictable for that day.
You can use the number of days since 1970, or the day of the month as a seed value
Just use a hashing algorithm on your date convert it to a number and define an upper bound using modulo e.g.:
$yournumber = hexdec( sha1($date) ) % 50;

Categories