I've created this code so that the user will not redirect onto the next page again. I set the maximum value on votenow button to 1 and once the user click the button again the value on the votenow button will not be added anymore since its maximum is 1. Everything works fine except that the user can still access the nextpage though the maximum value on the button was reached. Here's the code.
<?php
$errors = array();
$db = mysqli_connect("localhost","root","","registration");
if(isset($_POST['votenow']))
{
$votenow ="0";
$votenow1="1";
if($votenow != $votenow1){
$votenow = "update users set votenow = votenow + 1 WHERE votenow=0 LIMIT 1 ";
$run_vote = mysqli_query($db,$votenow);
echo '<script type="text/javascript">alert("hello!");</script>';
header ("Refresh:2; url=renewsys3.php");
}
else{
echo '<script type="text/javascript">alert("oh not again!");</script>';
header ("Refresh:2; url=renewsys2re.php");
}
}
?>
Can you guys help me or is there any other way so that the user will not enter the next page again? Btw, this is a voting system
The best way to use session:
$_SESSION['votenow'] = 0;
if (isset($_SESSION['votenow'])) {
if (!$_SESSION['votenow']) {
//do something
} else { // means $_SESSION['votenow'] == 1
// do something else
}
}
Redirect the URL to a different page (maybe homepage or any page) If the maximum vote is reached.
Let that code run before any other code so that the page won't load of the condition is true. It'll redirect immediately.
Related
i'm quite a beginner with PHP and i tried to make something to get xp when cliking the button. You just need to click and it gives xp, then it refresh the page to refresh the player's stat on screen.
<form method="post">
<p><input type="submit" value="Kill the mob" name="add20xp" /></p>
</form>
<?php
if (isset($_POST['add20xp']))
{
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
?>
The problem is that i want to prevent the user from smashing the button to prevent bugs and things like that... I tried to put sleep(1) but i can just keep spamming, wait the seconds and it works so it's not very useful.
Thanks for the help !
Save the last time the update was done in session state. Then, only allow the button to be pressed after (last time + 2 seconds) (Two seconds was chosen since that was the suggested interval in your original question).
if (isset($_POST['add20xp'])) {
if (!isset($_SESSION['last_post'])) {
$_SESSION['last_post'] = 0;
}
$currtime = time();
if ($currtime > ($_SESSION['last_post'] + 2)) {
$_SESSION['last_post'] = $currtime;
// ... process the post.
$add20xp =("UPDATE users SET exp = (exp + 20)"); // fix this line
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
}
As #Martin noted above in his comment, you want to do the update only for the user who pressed the button, which is the meaning of the comment "fix this line."
If you want to disable the button for 3 seconds after the form is submitted you can use this:
if(sessionStogare.getItem('submitted') === true){
document.querySelector('input[type="submit"]').disabled = true;
setTimeout(function(){
document.querySelector('input[type="submit"]').disabled = false;
sessionStorage.removeItem("submitted");
}, 3000);
}
document.querySelector("body").onclick = function() {
sessionStorage.setItem("submitted", true);
};
We will note the submission in the sessionStorage and check, if the form has been submitted every time we load the page. Then, we will disable the button and enable it after 3 seconds.
Change your php page to this:
// the beginning of the page:
<?php
// start a SESSION
session_start();
// setup a $_SESSION variable
if (!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
//
// now put the $_POST part
if (isset($_POST['add20xp'])) {
// check the time
$now = time();
if ($now - $_SESSION["timestamp"] > 2) {
// more than 2 seconds have passed since last $_POST
// update the time
$_SESSION["timestamp"] = time();
//
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
//
echo '<meta http-equiv="refresh" content="0.1" />';
exit;
} else {
// nothing, just let the page load like it is.
}
}
?>
Notice some important changes:
the use of $_SESSION vars -> these vars are stored and can be
retrieved at every page load -> you can use them to store the last
time an action took place
the $_POST part should be at the beginning
of the page -> otherwise after you send a form, you load the page ->
check the post -> then reload... it's not efficient
if you put the $_POST part at the beginning, you actually don't need the page reload with the meta tag -> because the data are already
updated
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';
}
}
my code is related to breadcrumbs.. that is it should display previous page or from where it is navigated and i achieved it partially , while im refreshing 2-3 times im getting the current page not the previous page.. so pl help me on this
my code lies in session.php as
$add = $_SERVER['PHP_SELF'];
if($_SESSION['pageadd'][1]!= $_SESSION['pageadd'][2])
{ $_SESSION['pageadd'][2]= $_SESSION['pageadd'][1];
}
echo $_SESSION['pageadd'][2];
if(($_SESSION['pageadd'][1]!= $add) )
{ $_SESSION['pageadd'][1]= $_SESSION['pageadd'][0];
$_SESSION['pageadd'][0]=$add;
}
What you want isn't a breadcrumb - it's a history for visited pages! This could be achieved with something like this:
if (!isset($_SESSION['pageadd'])) {
$_SESSION['pageadd'] = array();
}
// add page
$_SESSION['pageadd'][] = $_SERVER['PHP_SELF']
// only save last 5 pages
if (count($_SESSION['pageadd'])) > 5) {
array_shift($_SESSION['pageadd']);
}
Try to use $_SERVER['HTTP_REFERER'] it will return you previous url. However you need to store it in some hidden field or session like you are doing now.
Hope this help :)
I am trying to create a hit counter for my website and I have developed the following code for it. I have included the following code only in Codeigniter's main controller for my home page.
At first I thought the code was working fine but I just found that if I don't keep on browsing the pages then again go to the home page it doesn't update the data. I mean for example: If I go to my homepage for the first time then it updates the data, but after 10 seconds if I refresh the page it does't update the data. But if I keep refreshing it for 10 seconds then it works.
So could you please tell me how to get it update the data without having to keep on browsing the pages or refreshing the home page?
Thanks :)
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout')) {
$out = time() + 10; // I will change it to $out = time() + 60*60; later
$this->session->set_userdata('timeout', $out);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat+1
WHERE id = '1'");
} else {
$timeout_time = $this->session->userdata('timeout');
if (time() > $timeout_time) {
$this->session->set_userdata(array('timeout' => ''));
$this->session->sess_destroy();
}
}
}
edit
What I am trying to achieve is when an user visits the webpage for the first time, I want to update my database. Within 10 seconds (for example purpose), if the visitor again visits the home page, the database will not be updated. But after 10 seconds if he again visits the home page, I want to update my database.
Thanks :)
Your code says "if there is no timeout in the session, update the count". You want it to say "if there is no timeout in the session, or there is but it's old, update the count".
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout') || $this->session->userdata('timeout') < time()) {
$this->session->set_userdata('timeout', time() + 10);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat + 1 WHERE id = 1");
}
}
I'm not a CodeIgniter user, so I am assuming that you used its session facilities correctly; I just used them the same way.
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)
}