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)));
Related
I'm using a time clock system which, by default, records only the employee's entry and exit times. I'm customizing it so that it's possible to also record break times but I'm having trouble getting the break time to be subtracted from the total time.
This snippet of code is used to register the time between the check-in and check-out:
$time1 = Carbon::createFromFormat("Y-m-d H:i:s", $timeIN);
$time2 = Carbon::createFromFormat("Y-m-d H:i:s", $timeOUT);
$th = $time1->diffInHours($time2);
$tm = floor(($time1->diffInMinutes($time2) - (60 * $th)));
$totalhour = ($th.".".$tm);
The variable ($totalhour) receives the total value between the input register and the output register. It sends to the database in H.i format (hour.minutes), then another page searches for this information in the database and replaces the point (.) with (hr).
Based on this code, I did the same to get the interval start and end timestamps. I was able to get the time between the start time and end time interval with the code below:
$breakstart = table::attendance()->where([['idno', $idno]])->value('breakstart');
$breakend = table::attendance()->where([['idno', $idno]])->value('breakend');
$one = Carbon::createFromFormat("H:i:s", $breakstart);
$two = Carbon::createFromFormat("H:i:s", $breakend);
$breakone = $one->diffInHours($two);
$breaktwo = floor(($one->diffInMinutes($two) - (60 * $breakone)));
$totalbreak = $breakone.".".$breaktwo;
The $totalbreak variable stores the time taken between the start and end of the break. I was also successful in getting the time between this interval.
Now, I need the total time to be done by subtracting the time obtained from the record at the beginning of the interval to the record at the end of the interval.
I did with this code and got good result up to a point. Could you give me tips on how to get an assertive result in this case?
$totalhour = ($th.".".$tm) - ($totalbreak);
I tried to get the total time by subtracting the break time, but without success.
I have created two functions in a separate php file and want them to run over and over.
After function A completes, I want it to compare the current time, relative to the last time function B ran, and if more than 24hrs has elapsed (or whatever value I set it to), it runs function B, resets the next time for when it should be trigger to run, and continues to run function A. They need to run separately and not parallel since values altered in function A will affect function B and thus need to be separate. The ideal scenario is I have a config.php file where I set the time delay (in hours), but I can sort that out later!
I am stumped on how to get this while(true){} loop organized... any ideas?
Regardless of whether you end up doing it this way (because I think the comments about cron make some good points, and there are some other issues you may run into with a continuously running PHP script like this) here's a basic logic for executing the alternate function based on a defined delay.
// define the delay and initialize the timestamp
$delay = 86400; // 24 hours, for example
$last_time = time();
while (true) {
functionA();
// the next time functionB should execute is the timestamp for the last run + the delay
if (time() > $last_time + $delay) {
functionB();
$last_time = time(); // reset the timestamp
}
}
Would something of this nature be similar to what you're looking for?
while ($time > 13 && $time < 21)
You could have flags involved in each function as well. If a boolean flag is fired and is = 1, then continue on?
First of all, I know I am not supposed to as "code sample" here. Sadly, I am not a programmer and I have a situation where I need to update a line in a report to present to the customer, but I do not know how to do it.
I have access to PHP file report.php. In the same server and folder as report.php there is a file called report.csv. When report.php is loaded in browser, I want to show one line which will say:
Report.cvs is X minutes old that is all.
If the report is 10 days old, then also I can show the age in minutes. I dont need any complicated X days, Y hours, Z mins etc.
I am worried i might break something in server if I try to add myself since I am not programmer. Is there anyone who can show me what I need to add to report.php to make this work?
Looking through the documentation http://php.net/manual/en/function.fstat.php you might find that filectime ( string $filename ) may be useful.
Now if the file is consistently updated by users you may find that storing the creation/upload time in a Database like SQL/sqlite may be useful.
Ok so basically you need to get the time when the file was last modified, subtract it from the current time, convert the result to minutes and voilĂ .
Here's what that should look like:
$file = ''; // --- Path to the file
$filetime = filemtime($file); // --- File time
$now = time(); // --- Current Time
$fileAge = round(($now - $filetime)/60); // --- Subtract file time from current time, divide by 60 for the minutes and round the result.
echo basename($file).' is '.$fileAge.' minutes old.';
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');
So i have in a table tm_timekeep(id(pk), start(varchar), end(varchar)) [and a model for it] in a database with some time intervals in HH:MM format. For example:
id|start|end |
---------------
0 |10:00|10:30|
1 |11:23|11:55|
2 |13:15|15:39|
i would like to insert new rows and modify the existent ones if there are no overlappings between intervals.
if i would like to add as interval 11:57-12:40 would be ok, but 09:00-10:20 wouldn't because of 10:00-10:30, same for updateing a row. And if i would like to update a row, I need a function to check the condition before modifying the row. How should i do this?
My current code snippet:
public function checkInterval($start, $end){
$counter = 0;
$timekeepArray = Timekeep::all();
$start = date('H:i',Input::get('start'));
$end = date('H:i',Input::get('end'));
foreach($timekeepArray as $timekeep)
{
if($start <= $timekeep->end && $end>=$timekeep->start){
counter++; //in range
}
return counter;
}
}
After this i check the value of counter, but my problem is, that i always get 0 even if there are overlappings from input.
It's quite trivial - convert your time intervals to minutes, eg. 10:00 becomes 10 * 60 + 0 = 600 minutes, ends at 630 correspondingly.
Then, when you are trying to insert or update, and I would suggest you do it in Timekeep model, bound to 'saving' model event (see Model Events), you check whether:
1) Pick the last end time in minutes that is less than your new start time (that's a trivial SQL query)
2) See if there is any existing time in between that end time and your new end time - if there is, we have overlapping. Throw an exception, cancel model saving
There are several ways you could convert strings to minutes - you could store integers in MySQL (eg. 600) and then convert them to human readable hours either by defining getAttribute() or making your own methods. Or you could keep storing data as VARCHARs and do simple string manipulations (remove ':', multiply first part by 60) either in SQL or in PHP