Get Form data from html on page refresh(php) - php

I ran into a little problem with my college project again :(
<input type="text" name="timrem" value="" />
This is a hidden field that I want the data from.
if(isset($_REQUEST['timrem']))
{
$tim=$_REQUEST['timrem'];
}
This is the code used to get the value from timrem.
The variable timrem is used to initialize a countdown sequence on the page(implemented using javascript)
<span id="countdown-1" style="float:right"><?php echo $tim;?>
The value of the hidden field is dynamically changed via java script counter implemented.
sremtime=(parseInt(minRemain*60)) + (parseInt(secsRemain));
document.frmTest.timrem.value=sremtime;
this works fine when the page is submitted, ie, the time doesn't restart from the next page. But when the page is refreshed, the timer is restarted to the value of the $tim when the timer first started.
Is it possible to somehow get the value of the hidden input on page refresh?
And also, please comment on the approach taken to preserve the time elapsed to the next page. This is a project on online examination.

If you need your variable to persist across refreshes, you cannot rely on information passed back from client to server. The only information you can rely on is the information passed with the very first request, and that obviously doesn't include your time. The best solution I can think of is to store your timestamp in a session variable on the server:
session_start();
if(empty($_SESSION['timrem'])) $_SESSION['timrem'] = time(); // set this if it is the first time this page is loaded
$tim = time() - $_SESSION['timrem']; // $tim is now the number of seconds since the page was first loaded in this session
You do not need to pass the time back and forth between client and server to keep track of it, although your javascript will probably need it.

A good idea might be storing a timestamp either in your PHP page or in a database (for multiple users), and use it to generate $tim. Passing data on refresh doesn't seem possible as there is no request triggered.

How about you store a "target time" (what ever time remaining is counting down to) in your url. you could even store it in epoch time:
myurl.com/stuff.html?target_time=1359553896
that way when the page is refreshed you still have it with you and you can calculate time remaining from that. if you don't want it in your url, you could probably hide it on the page somewhere with a display:none style.
how about something like this:
http://jsfiddle.net/QpZcV/1/

Related

get time of when post is submitted php

I have a text box that submits text to an outside file. I am using
strftime("%I:%M:%S %p");
to get the time that it was sent, however, when the browser is refreshed the time changes. How do I make it so that it is the time of when the submit button is clicked and no the local time?
You probably have to store the time to the file so that when you display it content you read back the time as well.
Whether you use the client time or the server time is probably not really important, as long as you take this time when you write to the file and store this time with the data.

Not redrawing the page when the user presses the Back Button (Using $_GET variables in PHP)

I have a dynamic website with pages drawn using PHP.
Using the $_GET variable I am getting commands from the user, executing PHP based on the $_GET command, and drawing a page.
However, when the user presses the back button I want them to see the page that was dynamically drawn for them before, instead of re-executing code.
I've seen this done, but can't figure out how to do it.
For instance assume the following code:
if ($_GET['cmd'] == "time") {
echo "The current Unix timestamp is: " . time;
}
Clicking the url: somepage.php?cmd=time executes the code properly but when using the back button, re-executes the code. Is there a way using cache, or something else I don't know about, that will allow the user to see the time as it was when the page was drawn, instead of re-executing?
=========================================================================================
To try and be a little more specific, the pages and code that I am talking about perform multiple functions and alter MySQL data based on the commands given then draw the page.
I want to know if there is a way, when using the back button, to not re-execute but to just show the page that was drawn dynamically the first time.
I' not sure if this is what you are looking for, but it may be of help. Rather than using php get, you might use ajax and then implement this: http://www.nerdswithlives.com/2010/03/yui-ajax-browser-history-back-button.html
You could also have some type of variable stored every time a specific get command is executed, then check for that variable to determine which content to redraw on page load.
EDIT
From thinking more about your problem, I believe the answer lies with using PHP Sessions, and storing data on the clients machine. When a user clicks "back" he/she IS going to the cached page... so caching is not your answer. You need it re-drawn a specific way, but because you are using GET, the browser does NOT cache this... at least with back button functionality anyway. Your answer is to start a session on each page this dynamic content exists, store a variable like $_SESSION['sessionVar'] = 1; or whatever. Then dynamically change the variable depending on what was drawn on that page. Then, when the user clicks "back" you can check for whatever that variable is and get the data again. Get out of the mindset of using cache for this - you need to RE-DRAW whatever data the user saw previously. Sessions would be useful in this case.
you could take a look at using $_SESSION
if ($_GET['cmd'] == "time") {
$_SESSION['time'] = isset($_SESSION['time']) ? $_SESSION['time'] : time;
echo "The current Unix timestamp is: " . $_SESSION['time'];
}
You should use HTTP caching headers. There are three strategies:
Expire times
ETags
Last Modification times
The first one sets a date/time for the page to expire. This can be achieved sending a header:
header('Expires: Thu, 28 Apr 2012 16:00:00 GMT');
The main problem with this approach is that you cannot invalidate this cache. This means that if you want to redraw everything to update something on the page, you'll have to wait for the cache to expire.
ETags have better control, but are harder to implement:
$etag = md5($pageId);
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])
&& false !== stripos($_SERVER['HTTP_IF_NONE_MATCH'], $etag)) {
header('HTTP/1.1 304 Not Modified');
die;
} else {
header('ETag: '.$etag);
//draw the page
}
When a browser hits the page for the first time, the page is drawn and an ETag header is served. Next time the browser hits the page, it will send an HTTP request header If-None-Match with the previous ETag value. The server must compare this header with the current ETag, if they're the same, the server only needs to send an empty body and a 304 Not Modified status. The ETag can be anything that identifies the page content and version in an unique way.
Last Modification works similar to ETags, but instead of server-generated tags, it uses dates. Date comparison must be done considering later and previous dates as well.
Section 13 of the HTTP specification covers all these mechanisms and its gotchas. It's a hard reading, but it is worth.

How to calculate how much time the user is on a web page?

im making some statistic codes for my website (im a php developper). I want to calculate how many seconds/minutes the web user stay on any page (like google analytics do) but i have no idea of how to make this. Thanks for any help or scripts!
How are you gathering the data? The common options would be instrumenting the page using javascript, looking at webserver log files, in the server-side request handler or sniffing the TCP/IP traffic.
Doing it "like Google Analytics" implies the former. In which case the way to do it would be to grab a timestamp as soon as possible when the page loads (rather than waiting for page ready / onload event) and compare that value with the previous tiestamp (so you'd probably store that in a cookie). Then you need some way to send this back serverside, and a way of recording and reporting on the data.
Note that trying to fire an ajax call as the user leaves the page, e.g. via onunload, will not work reliably (the page launching the request is at the end of its lifecycle). The important thing here is the ASYNCHRONOUS part. And making a synchronous call will just have the effect of slowing down the website.
You might want to have a look at Yahoo Boomerang - although it doesn't support dwell time measurements out of the box, it's easy to extend. For a backend, you could do a lot worse than Graphite
You can fire an unload event in javascript when the user leaves the page, which sends an Ajax request to your server. Since this may not work in all browsers, especially if the network latency is high, also have a ping script (also with Ajax) which calls your statistics system once in a while as long as the user stays on the page (for example, every 10-60 seconds depending on the resolution you want).
If you want to do it in serverside i.e in php then probably you would need a table allocated for this. say "analytic"
First you need to add this script in every pages. that inserts these data into the table analytic which is $_SERVER['http_referer'] , current timestamp, remote address and current page URL.
Now the calculation part.
basically when a user first lands in your page $_SERVER['http_referer'] wouldnt be from your domain. Then keep the timestamp as the start time.
Now check the next time stamp. If the http_referer is same as previous records page URL then find the difference in the time stamp to know how much the user has stayed in a page.
More or less what am trying to say is find the time between each request from the user.
Disadvantage of this method: When user lands in a page closes it. its impossible to find the time on your site.
A quick and easy method I came up with is pretty useful.
On every page of a site where I want to track time on page, I include a tracker script.
I grab as much info as I can, and make a database entry, including the referrer, the requested/loaded page, user-agent, ip, timestamp, etc.
These timestamps, in conjunction with the user's ip, can be used to determine the time the user was on the previous page (including load time of current page).
The only drawback is that I can't determine time on the last page they visit (which isn't always a bad thing, I can reduce tracking idle time).
Bounces are identified by single entries by a given ip within a specified time period (an hour would probably be sufficient).
At page load create a date object, then when the page unloads create another and substract them. After that you can do an AJAX request to your tracking server, sending the elapsed time.
var startTime = new Date();
var endTime;
window.onunload = function()
{
endTime = new Date();
var elapsedSeconds = endTime.getTime() - startTime.getTime();
//Do the ajax request, sending elapsedSeconds
}

Countdown variable across many pages

I have a demo website for an e-test where each student is allowed 15 minutes for the whole exam (which comprises 5 subjects, each with 10 questions). I want it that, immediately a student clicks START on the home page, a countdown timer should start and update itself automatically. Actually, that is easily done for a single page.
The problem is if the student clicks to go the next page, I want the timer to begin from where it stopped on the previous page and continue counting down.
I thought of using SESSIONS but then how do I get Javascript to set the SESSION variable in PHP? The idea was to use AJAX but I do not know how to go about it.
Can anyone help me on it, even if it requires something other than AJAX?
PS:
What I want displayed is the number of seconds left, not the current time.
Thanks.
You don't have to know where it stopped on the other page.
You just want to know when the users clicked start.
Just save that in a database or a file even.
And on every request calculate the time left on the SERVER.
Since the client can be easily manipulated.
With the time left calculated on the server you can make a countdown using javascript on every page.
I found i simple way to do it, with a small search. Here
PHP:
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You can use an algorithm like this:
When the "start" event occurs, store the start time in a database.
Periodically send AJAX requests to a backend script. If the time has expired, return a response that ends the test.
There is not a real "timer" in this case -- just a start time, and logic to check if 15 minutes have passed since that time. If you want to display a timer to the user, the math will be straightforward.
You could just put the pages in IFrames and the countdown timer on the main page.
Simple, you store the timestamp of when the student first started the test and output it to each page. Then it's a simple matter of substracting current time from that timestamp to get elapsed time.
However, depending on Javascript is a very bad way of ensuring that this timer gets started. A better method is to force the user to click on an actual link/button, WITHOUT involving Javascript. You record the timestamp on the server then that hit comes in, and after that everything's fine.
start.php:
Start Test - Page 1
page1.php:
<?php
if(!isset($_SESSION['test_start_timestamp')) {
$_SESSION['test_start_timestamp'] = time();
}
?>
<h3>Question #1</h3>
etc...
The important thing is to never reset the timestamp value in the session once it's been set. Otherwise the test taker can simply click around until they reach a page where the counter's reset, and they can get more time for the test.

"New Content Avaliable!" PHP message checking a cookie

I'm trying to set up a cookie which would store the time when the user leaves a website, so in the next visit he can find a "There's new content" message (if any) - checked against his "last seen" stored time.
The things I'm stuck with are two : how do I send a cookie when he leaves the site ? And, then, how do I check that data when he comes back, compared to the last published content's time ?
This is the code I have by now :
<!-- I send the cookie -->
<?php
// How long should something be considered new for? (In seconds.)
// seconds * minutes * hours * days
// Default is 72 hours (3 days).
$stillnew = 60*60*24*3;
setcookie('CookiePublishing', time()-$stillnew, time()+60*60*24*30, '/');
?>
<!--I check the cookie and print -->
<?php
$entrydate = last_comment_time();
if ($_COOKIE['CookiePublishing'] < $entrydate) {
echo '<p>New Comment!</p>';
}
?>
As you see, I imagine a function called last_comment_time() that I have still to figure out, but my main concern would still be the moment in which the cookie is sent.
Many thanks for any input / alternative solution.
I don't think it matters when he leaves the site, but rather, what comments are on the page when it's loaded. For example:
12:00 comment1
12:05 comment2
==loaded at 12:10, sees comments 1-2==
12:15 comment3
==leaves site at 12:20==
==arrives again at 1:10==
In this case, he should be notified that there are new comments, since the last time he saw the page, there were only comments 1-2.
You may want to consider using PHP's built-in session handling and using $_SESSION.
Anyway, you may need to solve this problem by using two variables: one for the last access time and one for the current access time; when the page is loaded, set the last access time to the current one, then set the current one to the system's time. That way, you can determine content by the value of the last access.
For example:
<?php
// set cookies
session_start();
$_SESSION['lastAccess'] = $_SESSION['currAccess'];
$_SESSION['currAccess'] = time();
// send the cookies in the HTTP headers
session_write_close();
?>
...
<?php
$last_stillnew = last_comment_time() - 60*60*24*3;
if ($_SESSION['lastAccess'] < time()-$last_stillnew) {
print "<p>New comment!</p>";
}
?>
You have to use javascript.
One way to do this is to have the user's browser ping the server every five minutes or so. If the user doesn't ping the server for 6-7 minutes, he's gone.
edit: To give a bit more detail, what you need to do is send a blind ajax request to the server (so don't bother waiting on a response or anything). The script receiving the request should update the user's "last ping" field in your database or wherever. To find the last time they visited, it's "last ping" + time between pings.
This isn't really necessary if you just want to list new comments, as in that case you could simply record the time the user views the page, and display comments since then the next time the user visits (as FryGuy mentioned).
However the ping method does address your question of finding the amount of time since the user has last visited.
One obvious problem is if the user doesn't have javascript. To minimize the problems caused by this, update the "last ping" with PHP every time the user views the page.

Categories