Detect whether the browser is refreshed or not using PHP - php

I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.

When the user hits the refresh button, the browser includes an extra header which appears in the $_SERVER array.
Test for the refresh button using the following:
$refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&
$_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ...
<?php
session_start();
//The second parameter on print_r returns the result to a variable rather than displaying it
$RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));
if ($_SESSION['LastRequest'] == $RequestSignature)
{
echo 'This is a refresh.';
}
else
{
echo 'This is a new request.';
$_SESSION['LastRequest'] = $RequestSignature;
}
In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.

<?php
session_start();
if (!isset($_SESSION["visits"]))
$_SESSION["visits"] = 0;
$_SESSION["visits"] = $_SESSION["visits"] + 1;
if ($_SESSION["visits"] > 1)
{
echo "You hit the refresh button!";
}
else
{
echo "This is my site";
}
// To clear out the visits session var:
// unset($_SESSION["visits"]);
?>

If you mean that you want to distinguish between when a user first comes to the page from when they reload the page check the referrer. In php it is: $_SERVER["HTTP_REFERER"]. See if it is equal the page your script is running on. It may be the case that the client doesn't provide this information, if that happens you could set a cookie or session variable to track what the last requested page was.

To prevent duplicate form processing when a user hits the browser refresh or back button, you need to use a page instance id session variable, and a hidden form input that contains that variable. when the two don't match, then the user has refreshed the page, and you should not reprocess the form. for further details, see:
https://www.spotlesswebdesign.com/blog.php?id=11

If someone refreshes a page, the same request will be sent as the previous one. So you should check whether the current request is the same as the last one. This can be done as follows:
session_start();
$pageRefreshed = false;
if (isset($_SESSION['LAST_REQUEST']) && $_SERVER['REQUEST_URI'] === $_SESSION['LAST_REQUEST']['REQUEST_URI']) {
if (isset($_SERVER['HTTP_REFERER'])) {
// check if the last request’s referrer is the same as the current
$pageRefreshed = $_SERVER['HTTP_REFERER'] === $_SESSION['LAST_REQUEST']['HTTP_REFERER'];
} else {
// check if the last request didn’t have a referrer either
$pageRefreshed = $_SERVER['HTTP_REFERER'] === null;
}
}
// set current request as "last request"
$_SERVER['LAST_REQUEST'] = array(
'REQUEST_URI' => $_SERVER['REQUEST_URI'],
'HTTP_REFERER' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null
);
I haven’t tested it but it should work.

Related

PHP: display message if redirected from PHP file

I'm probably going about this the complete wrong way, but here's where I am at.
I have a page called adminquery.php and on it is a form. When that form is submitted, it calls a file called adduser.php
This page attempts to add the user sent by POST to a database and sends back one of two messages (added or updated) which should display on the adminquery.php page.
if ($row[0] == 1)
{
//update
$_SESSION['errMsg'] = "user updated";
}
else
{
//add
$_SESSION['errMsg'] = "user added";
}
header("Location: adminquery.php");
die();
adminquery.php displays the message
if(isset($_SESSION['errMsg'])){
echo "<p>".$_SESSION['errMsg']."</p>";
}
So far, so good. However, when I reload adminquery.php or access it from another page, I want it to not display this _SESSION message which is no longer applicable.
So I thought I would check the originating page when loading adminquery.php and, if it's not been accessed from adduser.php I would empty the message
$referringSite = $_SERVER['HTTP_REFERER'];
if (strpos($referringSite, 'adduser') == false) {
//$_SESSION['errMsg'] = $referringSite;
$_SESSION['errMsg'] = "";
}
The commented line is used to check the referring page and it displays adminquery.php as the referring page rather than adduser.php (which has been called but not displayed). It seems like unless the page has been displayed or an element on it clicked to reopen adminquery.php that it's not recognised as the referring page.
Is there some simpler solution I'm not seeing?
Setting an empty string won't clear the session variable. You need to unset it like so:
unset($_SESSION['errMsg']);
Also, you don't need to check the referrer. Since the user script sets that variable, the admin query script can just check if it exists, and if so, remove it after displaying the appropriate message.
You must unset this session variable.
if(isset($_SESSION['errMsg'])){
echo "<p>".$_SESSION['errMsg']."</p>";
unset($_SESSION['errMsg']);
}

Detect if user refreshed page

How can I detect if user refreshed the page with PHP?
I tried $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
But it didn't work for me because i have no-cache.
Here's What worked for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']);
if($pageWasRefreshed ) {
// Page was refreshed
}
else {
// Page wasn't refresh
}
Any water stones in this method?
Set a cookie for the first time when someone visits the page. So, when refresh check whether cookie exists or not, if yes the page is refreshed.
if (isset($_COOKIE['token']))
{
//The page is refeshed,
}
else
{
//first time user, set cookie.
setcookie('token');
}
You can do this multiple ways:
Set a session on the first time then check if the session is set or not.
Insert the client IP address in the MySQL database and check on every request if the user has visited before or not.
Now you have created your own logic and Google it how to implement this way
I suggest you use 2nd solution.

Clear POST Data Upon Refresh PHP

I have a form that re-submits on refresh. I've searched SO and have found nothing relating to my specific issue. I know it is better to have a separate PHP page, but for this specific project it needs to all be on one PHP page. I need the POST to reset when the page is refreshed so the form isn't automatically sent again.
Please note that I CANNOT have the page redirect somewhere else therefore I cannot use Post/Redirect/Get. The outcome I'd like to have is this: Person visits for the first time, enters correct code, script runs, then next time they visit or refresh the page etc, they have to complete the form again. Any suggestions would be much appreciated.
$code = '';
$hide = "<script>$('form').fadeOut(500).remove();
$('.wrapper').addClass('form-success');
$('.container').delay(1800).fadeOut(500);</script>";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$code = secure($_POST["code"]);
}
function secure($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (intval($code) == 1234) {
echo $hide;
$code = '';
} else {
echo "Failed";
$code = '';
}
Are you sure? It's perfectly fine to redirect the user to the current page, and I'm pretty sure that's your best option. So after processing the code, redirect the user to the current page, and a refresh will no longer re-submit the form. Just make sure you redirect using HTTP Response code 303; [it triggers a GET request][1]:
This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.
You can do this by using header after the submit has been processed (but before any html has been send to the user):
header('Location: '.$_SERVER["PHP_SELF"], true, 303);
if (!empty($_POST)) setcookie ("last_post", implode($_POST),time()+360000);
if (!empty($_POST) and $_COOKIE['last_post'] == implode($_POST)) $_POST = [];
With a POST request, we will add data to the cookies, with subsequent POST requests, we check them and if they are different from each other, we pass the parameters further.

How to prevent a user from directly accessing my html page by writing URL?

i want a hard coded Login Page (login.html), with no database.
If a person writes correct username and password, it redirects to (page2.html).
Now my problem is that if a person write the URL directly for page2.html , he will be able to access it, without any login.
Ideal Case => www.example.com/login.html => if Correct => www.example.com/page2.html
Problem Case => www.example.com/page2.html => page2.html , NO LogIN :(
You can control all this with a php session like this
//set the session on the login page
$_SESSION['loggedIn'] = true;
//on the second page you check if that session is true, else redirect to the login page
if($_SESSION['loggedIn'])
//allow
else
//redirect to the login page
header('Location: /login.html');
A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.
To make things simple, you can change your pages into php (e.g login.php).
Line 1: In your login.php page, you will first check if the username and password are correct, if they are, set the $_SESSION['loggedIn'] = true
Line 2: In your second page (page2.php), you will first check that the user did login by checking if the session have a value if($_SESSION['loggedIn']) {//allow processing}
Line 3: If that session variable is empty, then this means the user did not login, redirect him to the login page else { header('Location:/login.php');}
To start off: I have no idea how you would like to compare the password and username with something and check whether it's correct or not, but for now I would do something like this (again, this is without database).
You have 2 options: Either use a session as stated above, or the bit easier way: Just use theisset() function.
<form action="page2.php" method="POST">
<input type="text" name="userName" required>
<input type="password" name="password" required>
<button type="submit" name="submit">Send!</button>
</form>
page2.php will contain the next code:
if(!isset($_POST['submit']) {
//direct back to a certain page, could look like this:
header('Location: xxx.php');
exit();
//exit() prevents the code from running, it litterly EXITS the code as soon as it hits that line.
} else {
//direct to page2.php
}
Let's break it down: Why did I use the extension .php? Because you cannot do this purely with HTML.
Why did I use (!isset()) instead of isset()? Because a good practice is to think in security first, you don't access an important area and THEN check whether someone has lethal weapons or not. You check first and then you allow him either in or denie access. This is a quite simple and common way to prevent someone from accessing your page with the URL, however a SESSION is better and a bit more experienced practice.
This problem cannot be solved with a pure HTML solution. Your question is tagged as php so I'll base my answer on that:
Post your form to a php script (such as login.php)
Script checks the login details and sets a cookie
page2.html must be php instead, and checks for the cookie before displaying the HTML
Another option is using HTTP authentication, see this article for a tutorial.
You could block that page's access from external locations in your server securtiy settings,
then send the html of that page to the browser on successful login with fil_get_contents('page2.htm') in php. the php is run on the server so the file request won't be from an external source. you could overwrite html on the page using javascript or you could echo the contents on an if in php that will show the normal page on else
eg
if(isset($_GET['Login'])
{
//check login details
//if(....) //put your login check logic here
{
echo file_get_contents('page2.html');
}
else
{
//normal page's code goes here
}
}
Note:how to set the file to disallow external access is outside the scope of my answer
I had the same problem and found this and it works perfectly: (in javascript)
Just put it at the top of the document.
var x = document.referrer;
if (x == "page2.html") {
console.log(x);
} else {
window.location.href = "login.html";
};
change the default path for your website by using complete path to login.php. Next time when any of the user will type your url, they will be redirected to the given path which is yourpath>login.php
Hope it will help.
If you are using Asp.net, perhaps you can use TempData. They stay with the session between pages.
if (/*username and password are correct*/){
TempData["LoggedIn"] = "True";
} else {
TempData["LoggedIn"] = "False";
}
Then, when your controller tries to load page2 you just check the value of TempData.
var validate = TempData.Peek("LoggedIn");
if (validate == null || validate.ToString() == "False"){
return RedirectToAction("login");
} else {
/*allow access to page*/
}
Using .Peek keeps the TempData, as it would normally be marked for deletion if it was accessed. You also want to check it for null as it may have never been assigned if the user does not first go through the login page.
You can prevent that by checking if the user is already logged in
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: login.php'); //here you put your login page
exit;
}

Redirecting to the same page with PHP headers is not removing the GET request from the URL

I have a hangman game. My problem is that when they get to the win screen, they can refresh it infinitely and each refresh will increment their amount of wins (or losses if they lost), as it checks if the word is complete, it is, and ups their points.
I now made a SESSION variable to tell whether or not they have won. If they have, it resets the game.
My problem is that when they refresh with the GET request in the URL (how do I guesses) such as ...index.php?guess=G the game will refresh with G being guessed. I thought a header with Location set to index.php would get rid of the GET request.
Here's my detecting code:
if (isset($_SESSION["won"]) && $_SESSION["won"]) {
reset_game();
}
else if (isset($_SESSION["lost"]) && $_SESSION["lost"]) {
reset_game();
}
And the reset_game() function:
function reset_game() {
$_SESSION["word"] = generate_word("dictionary.txt");
$_SESSION["word-progress"] = turn_to_underscores($_SESSION["word"]);
$_SESSION["chances-left"] = 9;
$_SESSION["guesses"] = array();
$_SESSION["incorrect-guesses"] = array();
header('Location: index.php');
}
Why isn't this working?
I believe header("Location: index.php"); will remove all the get parameters from the URL.
I think you need to check whether your application did call the function

Categories