Include different content based on variables - php

I'm using this method to display different content based on the variable that was passed down from my previous page.
<?php
if (isset($_GET['click'])) {
if($_GET['click'] == 'person'){
file_put_contents('person.txt', ((int) file_get_contents('person.txt')) + 1);
include 'resultperson.php';
} elseif ($_GET['click'] == 'text'){
file_put_contents('text.txt', ((int) file_get_contents('text.txt')) + 1);
include 'resulttext.php';
} elseif ($_GET['click'] == 'online'){
file_put_contents('online.txt', ((int) file_get_contents('online.txt')) + 1);
include 'resultonline.php';
}
} else {
include 'resulttext.php';
}
?>
Problem is, when I hit refresh, the file_put_contents() function will be executed again. It's just a way that I use to track how many times users have clicked that button.
How do I prevent the increment of the integer being injected upon refreshing the page?
Or if there's a simpler method doing all this?

Using a session is probably your best bet, unless you don't mind that when the user closes the browser and visits the page again it will be triggered.
// This will be set to true if the user has the session variable set
$clicked = isset($_SESSION['clicked']);
// Check if get variable 'click' is set, and that $clicked is false.
// If 'click is set and $clicked if false, the variable $click is set to the
// value of $_GET['click'] (for example 'person'). Other wise it will be set to false.
$click = (isset($_GET['click']) && !$clicked) ? $_GET['click'] : false;
// Set the session variable 'clicked' if it isn't set so that the next time
// the user visits, we'll know
if (!$clicked) {
$_SESSION['clicked'] = 1;
}
if($click == 'person'){
file_put_contents('person.txt', ((int) file_get_contents('person.txt')) + 1);
include 'resultperson.php';
} elseif ($click == 'text'){
file_put_contents('text.txt', ((int) file_get_contents('text.txt')) + 1);
include 'resulttext.php';
} elseif ($click == 'online'){
file_put_contents('online.txt', ((int) file_get_contents('online.txt')) + 1);
include 'resultonline.php';
} else {
include 'resulttext.php';
}

If you want to track where the user has come from, you can use the referer field of the http header.
If that's not an option, you could have your click link to a php page that registers the click, and then do a header("Location: x.php"); to the page that displays the content.

With your actual code, you can't prevent the increment of the integer on a page refresh.
The question is: does it matter? How important and accurate you want your tracker to be?
There is a way to attach the increment to the button click, which is to use AJAX. You can attach a handler to the button click event, which makes the appropriate AJAX call to the PHP script.
This is not simpler, but it is simple.
Both this solution and your actual one can't prevent a malicious user to make HTTP requests to call your PHP script, incrementing your counter at will...

This should work, and is simpler, and more easily extendable:
<?php
if (isset($_GET['click']) && isset($_SERVER["HTTP_REFERER"])) {
$click = $_GET['click'];
if (in_array($click, array('person', 'text', 'online')) {
file_put_contents($click . '.txt', ((int) file_get_contents($click . '.txt')) + 1);
include 'result' . $click . '.php';
}
} else {
include 'resulttext.php';
}
?>

You could use an ajax-call to trigger that operation. This way the url gets called "behind the scenes" without reloading the content. I recommend this option; using JQuery ajax it can be as simple as writing a onClick function like function clicked(){$.ajax("yourClickCounter.php");} and then adding <button ... onClick="clicked()">...</button> to the html. Of course, you would then have to have the clickCounting done in a separate PHP-file, but it has the advantage of not reloading all the content every time the button is clicked.
You could use a session variable like $_SESSION['has_clicked']. This requires that you start a session first, with session_start()

To diferentiate when a user visits the page from your previous page, rather than hitting refresh, look at the $_SERVER["HTTP_REFERER"] variable. That variable will contain the url of the previous page from when the user came, but in the case of a refresh, that variable will not exist as the user hasn't come from any page (he didn't click a link to get to your page) instead was the browser that sent the request.
If your previous page is called 'mypage.php' for this matter, then replace your following line:
if (isset($_GET['click'])) {
for this one:
if (isset($_GET['click']) && isset($_SERVER["HTTP_REFERER"]) && strpos($_SERVER["HTTP_REFERER"],'mypage.php')) {
that should do what you want.
Update:
Above solution will not work as when hitting Refresh on browser the page will maintain the same Referer value.

Related

Storing a $_GET to $_SESSION when form is on every page Contact Form 7

I have a form on every page that is a quick navigation. Based on the value of the drop-downs it will redirect to a specific page. The URL after using it will look like /page?first=abc&second=def&third=ghi. If you leave the page and go to pageB the url will just say /pageB. I'm trying to create a SESSION for second if it's set and when it's no longer set (navigating to a different page not using the quicknav) still store the value when it was set. Here is what I have so far...
function storeVariable {
global $saved_second
$store_second = $_GET['second'];
$saved_second ='';
if (isset($store_second)) {
$_SESSION['second'] = $_GET['second'];
$sessionsecond = $_SESSION['second'];
$saved_second = $sessionsecond;
}
return $save_second
}
In the header I have
global $saved_second;
echo $saved_second;
The above code is fine for the initial page the quick navigation goes to. It shows the value of $saved_second in the header. I'm not sure how I would say
if (isset($saved_second) && (!isset($stored_second) {
USE SESSION THAT WAS CREATED WHEN $stored_second WAS SET
I thought something like...
if ($store_second != $sessionsecond){
but that doesn't work either because the session was created in an IF statement.
Then I tried...
IF (!isset($saved_second)) {
IF (isset($_GET['second'])) {
$_SESSION['second'] = $_GET['second'];
$saved_second = $_SESSION['second'];
}}
Any suggestions?

Cookie warning alert doesnt dissapear on first click

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!
When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

What is the best way to determine if my users can accept cookies/sessions

I need some help with some logic for my buying process on my website.
We have a 4 step buying process: results, customer details, payment details, order confirmation.
The results page simply outputs prices to the screen based on some query string parameters.
I then save lots of information to PHP Sessions variables for later use.
On the 2nd stage, the customer stage, I want to output some of these session variables to the screen which for the most part works.
In my code, one of the first things I do is check the existence of one of the session variables I set on the results page, just to check we are in business and the customers quote info is saving properly.
I have set up warning emails to myself to notify me when a user lands on either the customer or payment stage of the booking process but apparently the first session variable does not exist. I then display a friendly error message asking if they have enabled cookies in their browser.
We seem to be getting a lot of these warnings emails, alarmingly high. It doesn't feel like an accurate statistic of how many customers could arrive without cookies enabled.
The email alerts me of the current URL, the ref URL if there was one, the users IP address, and an output of all Session Vars they have saved (always none of course!)
I'm just stumped what to do next - are these really users or bots hitting the results page without cookies enabled which means they'll fail the test on the next page or could it be something else?
I have session_start() on the top of each of these buying pages so it's nothing like that.
Here's my customer page:
<?php
require_once "../includes/common.php";
$quoteShared = new quoteShared();
// Check if this is a direct page hit
if (requestSession("sessionnumber") == "") {
echo $quoteShared->directHit();
die;
common.php has session_start() at the top.
function requestSession($xParam) {
$value = "";
if (isset($_SESSION[$xParam]))
{
if ($_SESSION[$xParam] != "") {
$value = $_SESSION[$xParam];
}
}
return $value;
}
You can do it in javascript also, this way :
function cookiesAreEnabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0;
if (typeof navigator.cookieEnabled == "undefined" && cookieEnabled == 0){
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("test­cookie") != -1) ? 1 : 0;
}
return cookieEnabled == 1;
}
BEST WAY PHP
<?php
session_start();
if(!isset($_GET['testing'])){
setcookie('cookietest', 'somevalue', time()+3600);
header("location: cookie.php?testing=1");
}else{
if(isset($_COOKIE['cookietest']) && $_COOKIE['cookietest'] == 'somevalue'){
echo 'cookie enabled';
}else{
echo 'cookie not enabled';
}
}

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

PHP Conversion Tracking

I have 3 pages that I am trying to "track" so to speak. The signup process is 3 pages. Basically, I'm not wanting to count hits that are out of sequence (ie. if the user checks back into the thank you page (3rd page)) I don't want it to count a conversion again.
So something like this
1. User enters landing page +1 hit
2. User enters intermediary page +1hit
3. User enters thank you page +1 conversion
I know how to increment the count pretty easy for hits, but am unsure how to "not" count it if they are out of sequence.
You would set up a session variable so that on page 1 it was set to '1', page 2 = '2' and so on, but only set the variable if it is currently less then the current page number, so:
session_start();
if($_SESSION['cur-page'] < [CURRENT PAGE NUMBER]) {
$_SESSION['cur-page'] = [CURRENT PAGE NUMBER];
logHit();
}
Where logHit() tracks the page hit.
SESSIONS will solve your problem here.
On the first page do something such as:
session_start();
$_SESSION['page'] = '1';
// Store signup values in session
On the second:
session_start();
if ($_SESSION['page'] != 1 || $_SESSION['page'] != 3) {
header("Location: /page1");
exit();
} elseif ($_SESSION['page'] == 'complete') {
header("Location: /resubmit-error");
} else {
$_SESSION['page'] = 2;
}
// Store additional values in session
On the third:
session_start();
if ($_SESSION['page'] != 2) {
header("Location: /page2");
exit();
} elseif ($_SESSION['page'] == 'complete') {
header("Location: /resubmit-error");
} else {
$_SESSION['page'] = 3;
}
// Store additional values in session again and submit values to database or other source.
And finally the thank you page:
if ($_SESSION['page'] != 3) {
header("Location: /page3");
} elseif ($_SESSION['page'] == 'complete') {
header("Location: /resubmit-error");
} else {
$_SESSION['page'] = 'complete';
// Store data
}
On final submission of the third page redirect to completion / thank you page.
With this method a user wouldn't simply be able to return to the final page without re-completing the form.
Set a cookie or session variable called step. Before you run the tracking code, make sure the current step is greater than the step stored in the cookie, else don't track it. Usually for conversion tracking, it's desirable to use cookies over a session because you can track conversions for 30 days (or however long you want), rather than a short session which usually ends when a user closes the browser window.
On Page 1
$step=1;
if (!$_COOKIE['step']) {
setcookie('step',$step,time()+(86400*30),'/','.yourdomain.com');
//run tracking code (log database, whatever)
}
On Page 2+
$step=2;
if ($_COOKIE['step'] && $_COOKIE['step']<$step) {
setcookie('step',$step,time()+(86400*30),'/','.yourdomain.com');
//run tracking code (log database, whatever)
}

Categories