PHP: Detect Page Refresh - php

I have a page action.php on which I run an SQL query through the code, so that whenever the page is viewed the query runs like its like counting page views
<?php
mysqli_query("UPDATE ****");
?>
The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.
Question: How to avoid it ?
What I am looking for is a simple solution so that I can check
if( page was refresh ) //some condition
{
do
}

I found this snippet here, and it worked perfectly for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}

Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' || $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
if($pageRefreshed == 1){
echo "Yes page Refreshed";
}else{
//enter code here
echo "No";
}

You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.

If you just want to run it once for a user, I would set a session cookie and then use an if() statement.
<?php
session_start();
if (!$_SESSION['loaded'])
{
// insert query here
}
$_SESSION['loaded'] = true;
?>

i have solved the problem ... HURRAHHH with no session & no cookies
the solution is a combination of PHP : AJAX : JavaScript
the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is
function runQUERY()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","doIT.php",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following
<head>
<script type="text/javascript">
function checkRefresh()
{
if( document.refreshForm.visited.value == "" )
{
// This is a fresh page load
alert ( 'Fresh Load' );
document.refreshForm.visited.value = "1";
..call you AJAX function here
}
else
{
// This is a page refresh
alert ( 'Page has been Refreshed, The AJAX call was not made');
}
}
</script>
</head>
<body onLoad="checkRefresh()">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
and in your doIT.php simple add your PHP code which you were going to put in the normal page
<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>

//here you get the url behind the domain.
$currentPage = $_SERVER['REQUEST_URI'];
//if the session current page is not set.
if(!isset($_SESSION['currentPage'])){
//set the session to the current page.
$_SESSION['currentPage'] = $currentPage;
}
//check if the session is not equal to the current page
if($_SESSION['currentPage'] != $currentPage){
// if it's not equal you set the session again to the current page.
$_SESSION['currentPage'] = $currentPage;
//set the query you want to use
}

This can work in your scenario:
if(isset($_GET["token"])) {
$view_token = $_GET["token"];
} else {
$new_views = $views + 1;
// UPDATE VIEWS
$view_token = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
header("Location: ?token=$view_token");
}
If the user has a token in the URL, the view count will not update. Therefore, if the user tries to refresh, it will not update the view count. When the user does not have a token in the URL, the view count updates and refreshes the page WITH a token. It is thinking outside of the box but it works!

You can save a cookie that will be associated with the present page and if any link is clicked, update the cookie with the new page name.
Assuming the above is done in Javascript, you can send this updateCookie information to the server to notify about a new page hit.
Or another approach could be, you can specify a HTTP HEADER that specifies after how much time the cache expires on a page and that way, the browser wont even send you a request about page load/refresh.
See http://www.mnot.net/cache_docs/#IMP-SCRIPT for information about CACHING
Also , check out Etag vs Expires in HTTP - ETag vs Header Expires

if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
$_SESSION['status'] = null;<br>
}

Related

PHP cookie not working right after setting it

I am new to cookies, and tried to search for my problem, but couldn't find it.
My code:
index.php
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
When you open the page in the browser, the bottom part of the php code is executed, there shouldn't be a cookie 'time' so the body will be echoed with the onload="toggleoverlay()". This all works fine.
then when i click on the submit button to accepts the cookies, the page is reload, and the upper part of my php code is executed, a cookie named 'time' is created with the current time.
then the bottom part should be executed, but it still echos the body with the onload, even though i just created the cookie.
i also get the error when i'm trying to echo the cookie (saying the cookie does not exist). when i reload the page again manually then it works. But this is very frustrating since you need to accepts the cookie. then the page gets reloaded, and the overlay opens again.
I think this is because it takes some time creating the cookie and by then the other code has already been executed, but does anyone know how to fix this?
Thanks in advance.
The cookie is not set until the response is sent back to the client (browser). It is not available in your PHP until the next request from the client after that.
You could do next.
<?php
$cookie_set = isset($_COOKIE['time']);
if (!$cookie_set && isset($_GET['submit']) {
setcookie('time', date('Y/m/d H:i:s'), time() + 3600);
$cookie_set = true;
}
if ($cookie_set) {
echo '<body>';
} else {
echo '<body onload="toggleOverlay(0)">';
}
I have found a semi-solution, if the page is submitted, the page is reloaded, then after the cookie is created, i reload the page again en change the index.php?submit to index.php
like this
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
header("Refresh:0; url=index.php");
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
Like this it works, but it is not the best solution.

confusing about this cookies in redirecting system

I work in PHP. I want to redirect page after login to the last page that i want to visit, but I'm still stack at here in 5 hours and I still don't make it yet. This is the schema, I have 3 php file.
newest.php (before login),
signin.php (before login),
thread.php (after login).
I'm using cookies for this redirecting. First i went to the newest.php, then i clicked the button (go to thread.php). Then thread.php saw that you haven't loggin yet, then redirected to signin.php. After i fill the signin form then, i clicked the submit button (the signin.php), then I'm stack at signin.php (not going anywhere) even after I've loggin in, it should be go to thread.php automatically.
this is my code in newest.php & thread.php (not in signin.php):
$coopage='coopage';
$current_page='http://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
setcookie($coopage, $current_page,time()+86400,'/');
submit button in newest.php (it goes to thread.php):
echo "<center><button onclick=\"window.location='/thread/form'\">add new thread</button></center>";
in signin.php (after i clicked the submit button or in submit area, because form and after submit i made in the same page) (in the bottom of the page):
if(isset($_COOKIE[$coopage])){
$url=$_COOKIE[$coopage];
unset($_COOKIE[$coopage]);
header('location:'.$url);
}
note: in signin.php i also have another cookie setup before this cookie, is that the cause of this? or does it matter if i have 2 cookies setup in one page? Another cookie setup is like this (at the top of the page)
$cooval2='juna';
setcookie($coousername, $cooval2, time() + (3600 * 24 * 365), "/"); // 1 year
I would not use cookies at all.
Method 1
A possible way could be to store the link visited into a session variable and then when the user reaches the login.php page, provide a header redirect to $url given by the session variable.
Paste this code into all your pages on your website or the main container.
<?php
session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
For the login page you can have:
<?php
session_start(); // needed for sessions.
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "student_account.php";
header("Location: http://example.com/$url");
Method 2
A simpler solution by far is simply to have:
<hidden name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then redirect to that address once they log in.
However, this is only good if you have a login box on every page.
$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER'].
So save the HTTP_REFERER in a hidden element on your form, but also take note on that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
Method 3
Another common way to do this is to pass the user's current page to the Login form via a $_GET variable.
change your script so that is also tells the login page to remember where you are:
Note: $_SERVER['REQUEST_URI'] is your current page
header("Location:login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
Now check if it is populated, then send the user to this:
login.php
echo '<input type="hidden" name="location" value="';
if(isset($_GET['location'])) {
echo htmlspecialchars($_GET['location']);
}
echo '" />';
// Will show something like this:
// <input type="hidden" name="location" value="previousPage.php" />
login-check.php
session_start();
// our url is now stored as $_POST['location'] (posted from login.php). If it's blank, let's ignore it. Otherwise, let's do something with it.
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
$url = 'login.php?p=1';
// if we have a redirect URL, pass it back to login.php so we don't forget it
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location: " . $url);
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
$url = 'login.php?p=2';
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location:" . $url);
exit();
}
elseif(isset($_SESSION['id_login'])) {
// if login is successful and there is a redirect address, send the user directly there
if($redirect)) {
header("Location:". $redirect);
} else {
header("Location:login.php?p=3");
}
exit();
}
Your new cookie => local storage, make sure to have this code on every page you what to log the url on except for the login page otherwise it will redirect you back to the login page.
var currentPage = window.location.href;
localStorage.lastPageVisited = currentPage
This is then the code for the submit button and it will redirect the user to the last page he visited.
$(document).ready(function() {
$('button').click(function() {
window.location.href = localStorage.lastPageVisited;
});
});

Open Page Only After Redirecting

My question is may be foolish. But I want to know, if there is any code that prevent the page opening if tried with link but opens only after . if it's link is from another page.
for example, if i have a form on page contact.php and user gets redirected to page contact_success.php.
Now I want, if anybody tried to open contact_success.php page directly from browser address bar, it should not be get opened. It should be get opened only after form submission from contact.php page..
A simple way is just to use an if check on the contact_success.php page like
if($_SERVER['REQUEST_METHOD'] = "POST"){
//display page
} else {
echo 'You cannot view this page.';
//add redirect, if you like
}
Set a session or a cookie for the user in the contact.php, and then in the contact_sucess.php you can check if it exists.
for exmaple:
contact.php:
<?php
$_SESSION['visited_login'] = 'yes';
?>
contact_sucess.php:
<?php
if (isset($_SESSION['visited_login']) && $_SESSION['visited_login']=="yes") {
// output tanks
} else {
echo "go away";
die;
}
?>
You can use session for that example:
let say when you submit the contact form there is a page where in you will process the user input and i will use(refer to the #1)
contact_process.php
$_SESSION['success'] = 'success';
(this code will create a session)
then once success in processing the user input there is another page like(refer to # 2)
contact_success.php
if(isset($_SESSION['success'])
{
//Output if it is success
}
else{
header('location:contact.php');
}
(this code will check if session is existing if yes the desired output will show and if not it should turn back to contact.php)
you can easily learn session here http://www.w3schools.com/php/php_sessions.asp

stop other users to browse to some pages of my website

In my website i have used ajax at many places... But the problem is that the file, lets say some_ajax_file.php, is visible in the source code... I want that other users dont just type this in the url and go to this page... If they do so, they will then be redirected to another page...
I tried following code on that ajax page:
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$cur_page=curPageName();
and checked it
if($cur_page=="some_ajax_file.php")
//then redirect...
it is working if the type some_ajax_file.php in the url...but the problem is that the the ajax function where i used this some_ajax_file.php is not working....plz help me ....i m stuck....
You must have to search for $_SERVER['HTTP_X_REQUESTED_WITH']
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// I'm AJAX!
}
else
{
header();
die();
}
Create a Session at the time of Login
<?php
session_start();
// store session data
$_SESSION['Username']= Userid;
?>
and check the Session Available on that Page...
session_start();
if(empty($_SESSION['Username'])) {
//Redirect them to common page....
}
if the session availed then Show the page
Otherwise redirect them to login page....

Pass Onload Event Through Redirect

I am wondering if it is possible to call a script through a redirect. I have a contact form using PHP mail that echos a redirect back to the home page, like so;
...
header("Location: ../index.php");
...
Is it possible to add an onload event that gets passed to the redirected page? So when "index.php" is loaded from the redirect it calls a pop up thank you or something like that.
If you're sending them to the next page like this, you could either append some instructions to the end of the url, or you could store them in a session variable and check that upon the next page load - or even a combination of both.
session_start();
$_SESSION["redirect_url"] = "options.html";
header("Location: ../index.php?redirected=1");
And perform some type of check on the new landing page:
session_start();
if ( $_GET["redirected"] && $_SESSION["redirect_url"] ) {
echo "<script>
window.onload = function(){
var myWin = window.open( '" . $_SESSION["redirect_url"] . "' );
};
</script>";
}

Categories