i have got the following code which creates a random string:
<form name="randform">
<input type="button" value="Create Random String" onClick="randomString();">
<div id="xyz"></div>
</form>
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstringy = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstringy += chars.substring(rnum,rnum+1);
}
document.getElementById("xyz").innerHTML = ""+randomstringy;}
Now i want to export this string to a database in MySQL and make it valid for 7 days. The Goal would be, that the user generates a code, which would get stores in a DB, then the user tries to log in on another page using this code (which is then only possible if its still valid)
how would i proceed to do this using this code? i managed to export some other form input on another page to a database but thats the extent of my knowledge.
AFAIK, there is no specific TTL function for the records in mysql, however there is an Event Scheduler
which you can write queries to run periodically. But I think it would not be suitable for you, if you are expecting.
If I am you, then this is how I am going to solve this.
Session_Data
. Have columns user_id
, session_id
, session_created_at
.session_id
(type of VARCHAR(512)
) is for storing generated code.session_created_at
(type of TIMESTAMP
) to store when this code has been generated.When you post this form data, the backend service must store/update this generated hash in the database.
INSERT INTO Session_Data (user_id, session_id, session_created_at) VALUES (?, ?, NOW())
And whenever a user comes asking for a page, check this table to fetch the code associated with the user and validate the session_created_at
and current time difference is larger than 7 days. This will return a record if a code is there generated within last 7 days, otherwise will return none. Based on that you can allow/deny page viewing.
SELECT * FROM Session_Data WHERE TIMESTAMPDIFF(MINUTE, session_created_at, NOW()) <= 100080 WHERE user_id = ?
Alternatively, you can add those two columns into the User
table as well. But it is better you keep these information in a separate table.