How can I use MySQL and PHP to increase a value daily? - php

So I'm wondering how I can increase the value for the user by 10 daily or each time they log in?
I'm relatively new to PHP and have only made a login and signup system and need help learning.

You need a new column for each user in the database, this will store the value. You also need to store the last time they logged in (so you'll need a column for that). Each time they log in, in the login PHP code check to see if the current date is at least one day ahead of the last time they logged in. If it is, increase the value by ten; otherwise, leave it.

Related

calculate the time logged in by a user

i want to calculate the time for which the user remains logged in on my site, for example if user A logs in at 10 am and logs off at 10:15 am then store 15 minutes time and if he again logs in then also calculate that time and add to this 15 minutes and shows his total time in the system.
Quick example I can give you.
First add the required field in your database. i.e. In your users table, have a field called 'totalTime' or something.
If you're using SESSIONS, keep a value $_SESSION["start_time"] when the user logs in, and when the user logs out take the difference of the current time subtracted by the start time and add it to the totalTime field in the database for the specified user.
Any variation of that should work.
You could have a loggedIn field in your table, and a totalTime field. When the user logs in, record the time in the loggedIn field. When he logs out, get the logged in time, calculate the difference, and store it in the totalTime field, and zero the loggedIn field.
If the user logs in and the loggedIn field is not zero, the user did not log out, add the difference between the current time and the last loggedIn value can be added to the totalTime (or zero added - you would decide on a policy) and the loggedIn field updated to the new log in time etc.
If you want to collect detailed information about users, and not use simple statistics that google paralytics provide, you have a couple options, none of which are perfect solutions for anything.
Option 1:
You can simply record the time when users click on your page. The issue with this is that there is no way to see how much time a user has spent on your last page. But overall it will provide a good estimate, but will be very costly if yo have over 1000 users.
Option 2:
Record the time when user enters the website, and then have javascript ajax call that will record the time when user either logs out or closes the page. This will work if you allow users to be in a single window only.
Option 3:
Have javascript execute every minute or so and tell database that user is still logged in. Almost all databases can do over 1000 queries like that per second. If you optimize it, change database engine or do anything else you can easily get to 10k-25k queries per second.
Option 3:
If you are charging people money per minute then you can wrap the entire thing in java, or flash. however it is also not very secure.
Bottom line is: There is no perfect way to do it. You will have to hope that users have javascript enabled and track their time using background scripts, or do the whole session thing and hope that users log out. Or Track everything click by click and hope that your algorithm works well enough.
The below solution would be the most efficient one
The log table should have userid, unique_identifier, start_time, end_time
Logging in to the website will add a unique identifier for that session. It can be random number of 12 digits.
A variable $default_duration = 1440; is defined to calculate the session exipry due to inactivity. This variable should be set according to your server settings. 1140 is 1140 seconds (24 minutes), which is the default session exipry time
On user login, lets say a user loggs in by 2PM, the end time is set on login as well, which will be 2.24PM. This will solve the scenario of a user's session expiry due to inactivity.
On each page load, the end time is updated with "Current Time + $default_duration"
If a user clicks on Logout button, the endtime for that session is taken from the current time. This records the exact duration of the user.
Incase if the user logout and logins again, it would have a different "unique identifier" and the log time is updated against it.

User table in database is changed, how to update session?

Currently when the user logs in my site, a (PHP) session is started and his database row is saved in his $_session. I do so because the size of user's data is small for now, and this way I do not have to ask the database for user's data every time I need it.
The problem is that, when I want to add or change something during the development and I touch the database, the session is not updated this way. The user have to logout and login again to update the session. This is good for now since the site is in development phase, but in production this is not desirable.
I wouldn't delete session files, because people are lazy and I would avoid to force them to re-login every time something change in database, and I do not want to reload the session every X minutes. My solution for now is a boolean column inside the user's table, false by default, that I set true when I change the database. Every time a session is continued, session data will be updated if that value becomes true. Anyway this way I have to do a (small) query every time an user continues a session. I do not know if this will be a problem in production.
Is there an alternative / better way to solve my problem?
If I understand the problem correctly, one way to handle this would be every time a user row in the DB is updated that user's session data could be updated as well in PHP.
If it is not the user updating the records (such as an administrator changing a user's permissions) most likely you would want to force a logout of the user. If it is the user updating the records (such as changing information in their user profile) simply updating those values in the session variables may be enough.
In both of these cases you probably also want to provide a message to the user letting them know what happened.

Session in PHP and Mysql

I want to create a page on which I can see, who is logged in on my site.
For every user after logging in I create a session, and send a query to change the row "Logged" in mysql from No to Yes.
Then, on the page I use PHP to show everyone, who has Yes set in mysql, and it works.
But, I have a problem, which occurs when someone close the browser without clicking Logout - the query doesn't execute and the Yes value in mysql stays...
What can I do to create a page like this?
Instead of having a boolean value for logged in or out, determine a reasonable amount of time for the session to expire (e.g., 1 month) and then add that amount of time to a timestamp and store that in the database as session_expires or something. Then you can check if the user's session has expired whenever you do your login checks.
Additionally, to manually expire the session (for instance if a user logs out) just set the session_expires field to a timestamp in the past.
EDIT
I didn't have access to a computer over the weekend, so I couldn't properly update my answer.
If you need to see active users, one thing I've done in the past is to use a last_seen timestamp field that updates any time the user does anything on the site. Then, on your "users logged in" page, just query for something recent like "last seen in the past 15 minutes."
You cannot do anything about that, but defining a timeout. That means your initial call after logging in that sets your customer row to "YES" should be triggered on every request (or to spare resources, every minute) to update a date column in that very customer row. If no update comes in anymore, you define that customer as "not logged in anymore" and update the column to "NO"
The fact that the user keeps on staying logged in is due to the PHP SESSION TIMEOUT which may be configured in PHP settings php.ini.
Have a look at http://php.net/manual/en/function.session-set-save-handler.php to learn how to set a session shutdown handler (that will be called once the session becomes invalid). When the shutdown handler is called, set your current session's "logged" to false in the database. Still, it may take up to 24 minutes (default value in php.ini for session timeout - session.gc_maxlifetime = 1440 minutes).
Decrease this value (session.gc_maxlifetime) to 2-3 minutes and have a ajax function on each of your pages keeping the session alive. This will definitely increase your server's load but you will definitely have a better representation of the currently active users. You can decrease the value from php.ini or by usig ini_set(‘session.gc_maxlifetime’,30); in your code.
Regards

Making a time based Trigger in PHP

For example, if I want to set up a trigger that fires every hr passed since the current time, how would I implement that?
I am using PHP to write my backend code, essentially, if a user logged in, I give a sessionID, if there's no activity every hr , then session timeout. I think it needs to be implement in PHP right?
You use the cron job scheduler to run your script.
For Windows, you can try the Windows Task Scheduler. It provides similar functionality.
Actually, you don't need cron to do this.
Since you want to end the session if the user has been inactive for one hour, how about you do this.
When the user visits any page, update a $_SESSION variable with the current time.
Once the user browses to a new page, check if the current_time - last_time > 1 hour. If so, end the session and redirect them.
You should do this with cron scripts, not in PHP. Having PHP scripts running for hours is generally bad practice.
No need for job scheduling here. When you give them a session ID, store the session ID in a table in your database. Then do this upon every single request:
if session id row is found
if current time - last updated time > 1 hour
Do not allow access. Session is expired
else
update timestamp of session id row, setting it to the current time
allow access
end
end
Essentially: every time the user requests something, you can update a timestamp field in that session's row in your database. If the current time - last updated time > 1 hour, then the session is invalid and you should not allow the access.
If you wanted to schedule a job to go delete or otherwise deactivate rows that have expired, that's fine, but your session management scheme should not depend on that.
That said, if you don't have to roll your own session management, don't. It's fraught with lots of little details that are easy to overlook, and could result in leaving your site vulnerable. If you still need to roll your own, check out some of the OWASP materials about session management and authentication:
https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
either, set up a cron job that runs hourly, or instead set up code that retroactively calculates what needed to be calculated since the previous visit.
it would help emmensly if you were to describe what you are trying to accomplish in more detail.

How to limit number of logins at a time?

Hello I have a website. created using php,mysql. I want to set a limit like.. only 10 user can login my website at same time. How can I do that kind of a setting? any body knows the solution kindly help me..
Use a database table to store the number of logged in users but you need to come up with some way of imposing a time limit on those users. I would suggest a field in the table which notes their last activity. When a new user attempts to login you need to apply some logic like this (pseudocode):
if(<10users){
login
} elseif(any of the users have no activity for 30 mins){
remove that user and login
} else {
inform user of no space
}
You would need to update the last activity every time a logged in user visits a new page.
Go read up on sessions in PHP, then write your own session handler - the first time as a learning exercise. Then write your own session handler again, fixing all the bugs from your first attempt and adding in the facility to count active sessions.
Note that the normal behaviour for session handlers is that the session data persists even after the session has timed out - its up to the garbage collector (and optionally the session loader) to clear up session data which is stale.
i would override php session handling and store user sessions in the database. you can find a simple tutorial here: http://www.raditha.com/php/session.php
this way you can simply check if there are more than 10 valid sessions stored in your database table. though you have to think about handling logouts and timeouts, as some standard timeout like 30 minutes might not work well in your application.
If you want 10 user logged on your site, disable the login box if there are more than 10 users logged in.
This presume that you have a table in the db that records the users that are logged in the site. The login procedure will write a new line in the table. The logout procedure will delete it.
Simply count the numbers of rows in this table to determine the number of users.
as answered above you have to maintain a table which will store the number of users who logged in,but whenever the user logs out then decrement that value....whenever a new user logins increment that value by checking it with ur limit

Categories