I've researched this a lot but can't find a satisfactory answer; how do I create a PHP script that will generate a new number each day? Obviously I'm using this for a reason other than to generate a random number daily, but I won't go into that reason, it'll just make this question more complicated. So I'm asking this: How do I generate a random number which will change each day in PHP? Using MySQL will be no problem, but it must be automatic so I won't have to manually change it daily. (Here's my 'script' to generate a random number)
<?php
echo rand(1,100)
?>
Any answers are appreciated, Thanks
- Hugh
Use time() function to generate seed, then use regular rand.
This way you should't to store it anywhere and you always can regenerate it when needed.
function randomEveryDay()
{
$now = time();
$today = $now - ($now % 86400); //86400 = 1 day in seconds
srand($today);
return rand();
}
Or more interesting example without random at all.
function randomEveryDay() {
$now = time();
$today = $now - ($now % 86400);
$hash = sha1('salt string'.$today);
return intval('0x' . substr($hash, 6, 8));
}
Every day you will get the same number in $today, then use any cryptographic\non cryptographic hash function to generate "random".
This is fairly a simple task as long as you understand the basics of crontabs.
Step One: Create the script. This is basically going to be what creates the "text" then inputs it into the database via mysqli. For example, if we are generating a random number, what you have so far is good, you will just need to insert it into a database table. I recommend using a time stamp to give what day it was generated on
Step Two: Create a cronjob. Use the servers crontab to run a task every day, this can be done by adding this to the cron file: This will run a cron each new day.
00 01 * * * php path/to/your/generate.php
Step Three Fetch result from database by using the current date. If you are needing to display that text, pull it from the database using whatever the current day is from date() or DateTime
It's impossible to give a good answer without knowing exactly what you want to do, so this will generate a new number every day:
echo date('Ymd');
Related
sorry I am new to PHP and need some help/guidance on creating a counter that will work server side, so I guess update an initial value?
I need for example to start with a base number of 1500 and have that number increase by 1 every 2 minutes, obviously so any visitors will see an increased number each time the visit.
Would the initial value need to be stored in sql or can a txt file be updated?
Any help would be great,
Thanks
It can be done in SQL if you want it but a text file is OK too, just save a value (1500), then create a cronjob and let it execute a PHP file where you'll have to set up the code that executes an SQL query which updates that value OR the code to update that text file every 2 minutes.
Example:
# Every two minutes
*/2 * * * * /your/path/too/this/file/updatecode.php
In your PHP file:
$SQL = "UPDATE table SET columnname = columname + 1";
// etc...
// OR the text file update code
If you don't need to store it specifically for some reason, then you don't need to run cron etc... Take a time stamp of a specific point in time you want to start at. Then calculate minutes since and add it to your start number (1500)
//Start Number
$n = 1500;
$cur_time = time();
$orig_time = strtotime("2013-10-21 10:00:00");
//New Number + difference in minutes (120 seconds for 2 mins) since start time
$newn = $n + round(abs($cur_time - $orig_time) / 120,0);
// Output New Number
echo $newn;
And if you wanted it in one line for copy/paste
echo 1500 + round(abs(time() - strtotime("2013-10-21 10:00:00")) / 120,0);
You could do this without a database just using dates. work out the difference in time between two dates (the current date and the starting date when you created the script), then divide that down into the correct amount of milliseconds for 2 minutes, and add that to your initial 1500.
If storing it is needed a SQL database for this is probably overkill.
Create you number, serialize it and store it to a file. Load it from the file next time, unserialize, increment, serialize and save.
You can save a time stamp along with the number to the file to avoid having to run some job every 2 minutes and instead calculate the correct value when you load the number back from the file.
Something like this (but error checking etc should be added and I haven't actually tried it to make sure the calculation is correct... but the main idea should be visible).
<?php
if(file_exists('mydatafile')) {
$data = unserialize(file_get_contents('mydatafile'));
// Calculate correct value based on time stamp
$data['number'] += round((time() - $data['timestamp']) / 120);
}
else {
// Init the number
$data["number"] = 1500;
}
// Print it if you need to here
// Update time stamp
$data["timestamp"] = time();
// Serialize and save data
file_put_contents('mydatafile', serialize($data)));
How can I check the current timestamp in MongoDB?
Currently I use a query that looks like:
"last_visit": {
"$lt": NumberLong(1373779876)
}
I store that query, and then I have a cron job that makes it run every minute.
If one of my users hasn't logged in since some timestamp, I can know it.
But the NumberLong generated isn't right, as I am currently using time() - 14days via PHP, the resulting NumberLong should be the result of something like:
timestampNOW - someTimestamp (that I generated in PHP)
My current solution stays an absolute date in the past, instead of a relative date such as timeRIGHTNOW - 14 days.
I believe I need a native Mongo command within my query...
I'm not entirely sure what you're asking for, but I think there are two options:
a) You want to construct a query using php that asks mongodb for all users that haven't logged in the last two weeks
<?php
// two weeks ago. note that time() returns number of seconds, not milliseconds
$date = (time() - (14 * 24 * 60 * 60)) * 1000;
// construct query: { "last_visit" : { $lt : $date } }
$query = array( 'last_visit' => array( '$lt' => $date ));
$cursor = $collection->find($query);
// you can now iterate $cursor
?>
b) You want to perform a mongodb query in javascript ('native Mongo command')
db.Foo.find({"last_visit" : {$lt : ISODate().getTime()}});
calling ISODate will create a new ISODate object representing the current time, and getTime will return the number of milliseconds since the UNIX epoch. I don't know how you can pass that query to the PHP mongodb driver, but it should be straightforward.
Current timestamp rounded to whole second:
Timestamp(new Date().getTime()/1000,0)
Timestamp 14 days ago:
Timestamp((new Date().getTime()-(3600*24*14*1000))/1000,0)
I have a PHP file that randomly generates an image from a folder on every refresh. I downloaded it from here (which also has an explanation).
Instead of randomly choosing images, how can I have it change the image hourly? For example, I would like it have the same image for an hour, and then change when that hour is up. Basically, a new image based on some time interval.
Thanks for the help.
Find line
$imageNumber = time() % count($fileList);
And replace it with
$imageNumber = (date(z) * 24 + date(G)) % count($fileList);
That should work for you.
I'd say you need a random oracle function. Basically, it's a random() function that takes an input and generates a random number, with the guarantee that all calls with the same input will give the same output.
To create the value you pass into the oracle, use something that'll change hourly. I'd use julian_day_number * 24 + hour_number or something of that variety (just hour_number isn't good enough, as it'll repeat itself every 24 hours).
Then, whenever your page loads, generate your hour number, pass it through your oracle, and use the result just like you use your random value now. It'll still appear random, and it'll change once an hour.
Hope that helps!
Edit: Random oracles don't need to be fancy - they can be as simple as (stolen blatantly from this answer to a different question):
int getRand(int val)
{
//Not really random, but no one'll know the difference:
return ((val * 1103515245) + 12345) & 0x7fffffff;
}
Keeping it simple, put 8 different pics in img/ named from 1.jpg to 8.jpg, then:
$imagePath = sprintf("img/%s.jpg", (date('G') %8) +1);
with G param being:
24-hour format of an hour without leading zeros.
Now you are sure that you have a different pic every hour, and everybody sees the same.
EDIT: narrow or widen the repetition period adjusting modulo, 24 has a few divisors [1, 2, 3, 4, 6, 8, 12].
I'm wanting to display on a php page the difference between the current server time and a datetime row plus a row that has milliseconds in it, so I guess the equation would look kind of like ((Datetime+Milliseconds)-Server Time).
The only problem is, I'm not sure how to do it in code. I can currently get the difference between the datetime row and the current time with echo strtotime($row['date_added']) - time(); When I try adding the row that contains the milliseconds, date_mil, I get a really long number.
The date in the row date_added looks like 2012-05-25 16:55:06 and the value of the date_mil is around 218238.
I'm still learning how to do all of this, and this has me confused. Thanks for the help!
I just solved my own problem.
$difference = time() - strtotime($row['date_added']);
$milliseconds = round(($row['date_mil']) * .001);
echo $milliseconds - $difference;
I need to compare two dates to show an edit link if it is within 5 mins after the post was made, in PHP. If more than 5 minutes have passed, don't show anything.
$answer_post_date = get_the_time("Y-m-d");
$current_date = date("Y-m-d");
$formated_current_date = strtotime($answer_post_date);
$formated_answer_post_date = strtotime($current_date);
At this point I have two values:
1274414400 ($formated_current_date)
1276056000 ($formated_answer_post_date)
I am not sure what to do next to check if the current date/time is > 5 mins from the answer post date.
Any suggestions would be great.
All I really need the answer to be is a Boolean (yes/no) and if yes, display the minuets left to show the link to edit.
You're only handling dates, how are you supposed to know if the difference is 5 minutes?
Anyway, I'd say the majority of the PHP code that uses the default PHP functions is at least somewhat broken. The problem is you, despite a unix timestamp storing the correct point in time something happens, it does not store timezone information. See here.
So, forget using only date and strtotime. Use the datetime extension.
Store in the database the Unix timestamp and the timezone (by timezone I mean e.g. Europe/Lisbon). Then:
$tz = new DateTimeZone($timezone);
$answer_post_date = new DateTime("$timestamp");
$answer_post_date->setTimeZone($tz);
$current_date = new DateTime("now", $tz);
$diff = $current_date->diff($answer_post_date);
if ($diff->format("a") > 0 ||
$diff->format("h") > 0 ||
$diff->format("m") >= 5) {
//more than 5 minutes have passed
}
Of course, for comparing dates, you can always compare the timestamps.
My understanding of what you need to do:
$delta = ($formated_current_date - $formated_answer_post_date) / 60; // in minutes
if ($delta < 5) {
// show $delta
}
EDIT: Like others pointed out, this alone will not fix all of the issues at hand. As I see it, the smallest change to your current code would be to use a date format with higher granularity - such as "Y-m-d H:i:s". This being enough, like others pointed out, is contingent on the post's date being in the same timezone as your system.
I don't see the need to do a round-trip to a string format and back, regardless of how efficient or reliable it is.
date() will default to calling time() which you can call directly and get the current time in seconds as a Unix epoch timestamp (which is what you're trying to end up with in $formated_answer_post_date). You need to look in the WordPress docs to find the equivalent based on the post's value.
Then you can do a simple comparison of seconds. 5 minutes is 300 seconds.
You will still need to check that the code can assume the timezones of both values will be the same.