hello i would like to know at what time any particular session was set or started ?? is this possible by php
i know session set or not can be checked by
if(isset($_SESSION['name'])){
/////////////
}
but here i want when the sessoin was started so that
if($_SESSION['name'] // started on date is greater then last 5 minutes
){
// do this
}
When you start the session you could save when it was started in the sesson.
session_start();
$_SESSION['startDate'] = date();
The code will change on how you want to store the date but that the crux of it. If you want to know when you set exactly $session['name'] you could use an array to store the name data with the date.
Related
I would like to limit the access of a function i've created to once every 24 hour based on the users IP address. I would also like the PHP script to delete the MySQL record if it's older than 24 hours.
If the user already has used the function within 24 hours, show them a message and prevent the script from continue running.
If the user already has used the function but 24 hours has passed since he used the function, delete the MySQL record and let the script continue running.
I'm lost and as you can see i am also missing some statements for deleting old records (-24 hours)..
Could anyone provide me with an example of how to do this? Thanks
Get client's IP address and store it with current date and time if the record doesn't exist.
Fetch the record and add 24 hours to its date and time value and check it with the current date and time every time the script is executed.
You need if else conditional statements to check if the 24 hours time is over or not. Based on that, you will control the execution of the function you want to.
I think I don't want to write much of theory. Here, I've written the pattern what the code looks like:
if(!$record_in_db) {
// create record with the client's ip address and the current date and time
// invoke the function you want - This is the code to trigger the function first time for the new IP address
} else {
// fetch_record_from_db
// add 24 hours to its date and time value
// check it with current date and time
$record_date_time = new DateTime('22-12-2016 22:45:20'); // this value should be fetched from database
$record_date_time_by_24_hours = $record_date_time->modify('+1 day');
$current_date_time = new DateTime(date('d-m-Y H:i:s', strtotime('now')));
$date_time_diff = $current_date_time->diff($record_date_time_by_24_hours);
if($date_time_diff->invert == 0) {
// Do something
} else {
// update the date and time of the record to NOW which is current date and time
// invoke the function you want
}
}
I can't write you the whole code. I could only give you some hints. You need to build the code from it. Hope I've given you right hints that could help you.
I was hoping somebody could help me out with how I would implement a 'Remember me' function in Parse.
When the ParseUser is first created, a ParseSession is also created with them, however this has an expiry date of 1 year. The problem is, the expiryDate is read-only, so I'm not able to change this. Even then, I am confused as to how these ParseSession's work, as they don't actually store any cookies.
Should I just delete the ParseSession's that are automatically created on registration, and make my own cookie and session to deal with this, or does Parse provide an easier way?
Edit with code I have tried so far:
So far I have tried to do this without Parse, using PHP's own cookie functions:
$user = ParseUser::logIn($email, $password);
$_SESSION['mySession'] = serialize($user);
$_SESSION['start'] = time(); // Taking now logged in time.
if ($rememberMe) {
// End session in 1 month.
$_SESSION['expire'] = $_SESSION['start'] + (31 * 24 * 60 * 60);
} else {
// End session in 1 hour.
$_SESSION['expire'] = $_SESSION['start'] + (5);
}
$parseSession = $user->getSessionToken();
// Note I got stuck here as I realised the expiryDate is readOnly in the docs.
Note that this code right now isn't working as expected since the session I am creating using
session_start();
ParseClient::setStorage(new ParseSessionStorage());
seems to be creating a session that lasts only the browser session - but I will look into this and I believe/hope it's something to do with PHP storing the sessions (I checked the .ini and it said on Windows I need to configure it manually which I have not done yet).
Here is my code
i have html link like this
<?php echo $pro_name;
these php values coming from database it has (thousands of) number of results, here i need to set cookie for this links.
If its clicked means i need to store that links in cookie and i need to show last five viewed links in another page.
If I understand, you just need to bind the setting of a cookie to the clicking of the link?
If so, you need to add an ID to your <a>:
In English
Then bind some cookie-setting code to the click event:
(Using jQuery)
$("a#mylink").bind("click", function() {
$.cookie("TR_LNG", "English");
});
Edited. Set expires time(for example for 30 minutes):
30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });
You don't need cookies for this. If I undertsand your problem, you simply need to keep track of the last N requests to your app from a certain user. You need users to be associated with a session, and at the top of each and every page you want to track you need to:
session_start();
$hits = $_SESSION['last_hits'];
array_push($_SESSION['last_hits'], getExternalUrl());
if (count($hits) > 5) {
array_shift($hits);
}
You'd better implement a framework instead of manually adding this snippet at the top of every PHP file. Also note that I used getExternalUrl() because if the PHP server is reverse proxied, the request path may not contain the actual URL (not sure what you really need, tough). Appending the page token to the query string may be ok, too, but it all depends on your needs.
I'm once again asking for the SO community for a little help.
I'm modifying a Joomla "quiz" component to make it behave the way I need it to.
What I'm trying to do now is to change the "refresh" behavior of the component. Basically, every quiz has a timeout, i.e., a time when the quiz is no longer accessible to the user so when the timer gets to 0, the quiz is submitted and so on, but the default behavior of this component makes it that whenever the page is refreshed the timer will reset to the initial set time (let's say, 10 minutes)
The thing is I want to be able to have the timer continue from where it left of in case of a refresh.
I haven't used PHP since 3 or 4 years ago so I'm kinda lost.
To be able to achieve the desired behavior I'm setting up a cookie that will store (via implode) the initial time (when the quiz was opened) and the "now" time (on load it's set to 0 but upon refresh I want to "update" the cookie to store the reload time).
With the initial time and the now time, I'll be able to calculate how much time has passed and place the timer from where it left off.
The thing is, I'm trying to "update" the cookie with a javascript 'onbeforeunload' so that I can manage to get the refresh time into the cookie. But for some reason, it's not doing anything at all. When I go to see the cookie contents everything is still the same from when the cookie was set.
I know that in order to update the cookie I'll have to delete it and then set it again, but I'm being unsuccessful.
Heres the sample code:
//This is responsible for setting the cookie (via PHP):
<?php
$name = "progress";
$now = 0;
$time_diff = 0;
$expire = time() + 3600;
$data = array(time(), $now, $time_diff, $this->quiz->time_limit);
//$var = implode(',', $data);
if(isset($_COOKIE[$name])) {
/* If defined, update the timer */
} else {
setcookie($name, implode(',',$data), $expire);
}
echo $_COOKIE[$name];
echo "<br />";
echo $this->quiz->time_limit;
?>
And this is to detect the "refresh" event (with Javascript that will run PHP):
window.onbeforeunload = function() {
<?php
$name = "progress";
$list = explode($_COOKIE[$name]);
//delete cookie
setcookie($name, "", time() - 3600);
//Update the fields
$list['1'] = time(); //now - refresh time
$list['2'] = $list['1'] - $list['0']; //time_diff
//Set the cookie again
setcookie($name, implode(',', $list), time() + 3600);
?>
}
Can anyone point out what is wrong with this code?
As has been said in the comments, JavaScript cannot run PHP code like that... but if you use AJAX then you can. Now with the code you posted for us to see, if you load up your page in the browser and view the code your function will look like this:
window.onbeforeunload(){
}
So it's no surprise that nothing is happening with your cookies when you are closing your browser. Now, without seeing your other functions it's hard to tell exactly what is happening but you can use PHP and JavaScript intertwined but in a different fashion. Let me explain this with an example.
window.onbeforeunload(){
var name = <?php $name='Steve'; echo($name); ?>;
console.log(name);
}
If you had this code and loaded the page in the browser you would no longer see the PHP code, but instead would see this:
window.onbeforeunload(){
var name = 'Steve';
console.log(name);
}
With that being said, here are a few links you might find helpful.
JavaScript Cookies
Set/Get Cookie using PHP and JavaScript
Simple AJAX - PHP and JavaScript
The following code is within an ajax call. I'm trying to make sure people don't vote on questions with a certain id too often using sessions.
So they click a button, which executes the following php code:
$id=$_GET["id"];
if ((isset($_SESSION["$id"]) && ((time() - $_SESSION["$id"]) > 180)) || (!isset($_SESSION["$id"]))) {
// last vote was more than 3 minutes ago
$_SESSION["$id"] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
So I'm creating a session variable for each question id which holds the time() of their last vote. I would do this with cookies, but they can be disabled.
Currently, there is a bug somewhere with my logic, because it allows the user to keep clicking the button and adding as many votes as they want.
Can anyone see an error that I have made?
using sessions to prevent multiple voting makes very little sense.
sessions do use cookies with the same drawbacks
unlike strings, variables in PHP should be addressed without quotes. such a false usage WILL cause an error someday.
I see no point in checking for isset($_SESSION[$id]) twice.
There was a bug in PHP which disallowed numerical indices for the $_SESSION array. Dunno if it was corrected nowadays.
As it was pointed out by Sajid, you have to call session_start() before using $_SESSION array.
now to the logic.
to me, it seems the code won't let anyone to vote at all. as it won't pass isset($_SESSION[$id]) condition for the first time and won't let $_SESSION[$id] to be set and so on.
it seems correct condition would be
if ( (!isset($_SESSION['vote'][$id]) OR (time() - $_SESSION['vote'][$id]) > 180) )
You need to call session_start() to start the session before any headers are sent. Otherwise, sessions will not be enabled unless the ini setting to autostart sessions is on. Also, your server must be correctly configured to be able to store session files (usually a writable tmp dir is needed). See more about sessions here: http://www.php.net/manual/en/ref.session.php
There might be a problem with the if statement. Try the following
$id=$_GET["id"];
if (((isset($_SESSION[$id]) && ((time() - $_SESSION[$id]) > 180))) || (!isset($_SESSION[$id]))) {
// last vote was more than 3 minutes ago
$_SESSION[$id] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
Perhaps time() returns milliseconds and you should compare to 180000 instead of 180.