PHP session getting lost when using onclick - php

i redirect to a page in the same folder using onclick event to show information for different dates , but when i use onclick then it doesn't work , it only works if make a button and put everything in side a form , don't want to use buttons because it doesn't fit the style of the page. Is my code wrong or do i have to do some setting to keep the session alive.
Page A
<php
//enable sessions
session_start();
$todaydate=new datetime();
$todaydate=$todaydate->format("Y-m-d");
//check if session is not set
if(!isset($_SESSION['curdate'])){
$_SESSION['curdate']=$todaydate;
}
// get monday's date
$daynumber=date('N',strtotime($todaydate));
$daynumber=$daynumber - 1;
$mondaydate=date('Y-m-d',strtotime($todaydate . ' - '.$daynumber.' day'));
$_SESSION['mondaydate']=$mondaydate;
$i=0;
While($i != '7'){
$buttondate=date('Y-m-d',strtotime($mondaydate. ' + '.$i." day'));
echo '<span onclick="location=','B',$i,'.php'",'">',$buttondate,'</span>';
$i++;
}
?>
Page B1
<?php
session_start();
$choosedate=$_SESSION['mondaydate'];
$$_SESSION['curdate']=$choosedate;
include_once("a.php""):
?>

Related

PHP - Change Variable Name

I have two 'includes' php pages, Page 1 and Page 2.
Page 1 displays contents for today, Page 2 displays contents for yesterday.
I set a cronjob to copy contents of Page 1 to Page 2 every 0:00am daily.
On the main page (the page that contains this page 1 and page 2), I have:
$date = date("d/m", strtotime("now"));
$dateyes = date("d/m", strtotime("-1 day"));
Then on Page 1, I have:
echo $date;
On Page 2, what I need is:
echo $dateyes;
But due to the cronjob, I only get
echo $date;
on that Page 2. Is there a way I can change that $date to $dateyes on that Page 2?
Not really sure how copying a php script from day to day should work in practice, but if need this pattern for some reason, simply replace your current echo $date; to echo $is_page1 ? $date : $dateyes;
Where $is_page a variable that check which page is loaded via something like:
$is_page1 = $_SERVER['SCRIPT_NAME'] === 'page1.php';
Or:
$is_page1 = basename(__FILE__) === 'page1.php';
I found a solution.
On the mainpage.php, I checked if "dateyes" already exists in page2.php, if it already exists, script does nothing but if "dateyes" does not exist, my script searches for "date" in that page2.php and since what I needed on page2.php was "dateyes", I replaced "date" with "dateyes".
On mainpage.php
$datetod = date("d/m", strtotime("now"));
$dateyes = date("d/m", strtotime("-1 day"));
$file = file_get_contents('../includes/page2.php');
if(strpos($file, "dateyes") !== false){}
else {
$str=str_replace("datetod", "dateyes",$file);
file_put_contents('../includes/page2.php', $str);
}
So I no longer worry about the cronjob which automatically copies $date from page1.php to page2.php everyday at 0:00am because the first person who loads/views the page (mainpage.php) is automatically going to change the $date in page2.php to $dateyes which is what I need.

Autoincrement url for anchor link

I am trying to make anchor links for different sections in the page.
#section1
#section2
But, the url isn't being updated each time I click the href link
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}
<?php echo ''.'Next Section'.'';?>
When I echo the counter I can see it being updated upon refresh but I want to be able update the anchor section without refreshing.
Thank you
You need to actually increment the value in the session and not just what is currently stored in the session.
// If there is a value in the session, then increment it.
if(isset($_SESSION['counter'])) {
$_SESSION['counter'] = $_SESSION['counter'] + 1;
} else {
$_SESSION['counter'] = 1;
}
// Now, use the value which you have set.
<?php echo ''.'Next Section'.'';?>

How to prevent the user from abusing a button?

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

PHP setting session variables on button click

When a user click either 4/6 'Snacks Per Shipment', and weekly/fortnightly/monthly 'Shipment Frequency', a function displays the details on the right hand side above the button.
I'm a noob developer looking to store whatever information a user chooses, as a session variable once the button 'Choose your snacks' is clicked. In this example, I would be looking to store 4 and fortnightly.
Here is my PHP code when starting the session
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_POST['choose']))
{
$unit = document.getElementById('unit').innerHTML;
$frequency = document.getElementById('frequency').innerHTML;
// Set session variables
$_SESSION["unit"] = $unit;
$_SESSION["frequency"] = $frequency;
}
?>
Here is the code related to the button
<div class="pricing-button" method="POST">
<a href="session.php" class="btn btn-yellow btn-rounded btn-lg"
name="choose" type="submit">Choose Your Snacks</a>
</div>
Here is my code related to scraping what the user chooses
<script>
function change(unit){
document.getElementById('unit').innerHTML = unit;
}
function frequency(frequency){
document.getElementById('frequency').innerHTML = frequency;
}
</script>
And here's where i'm testing if the session variables are working or not
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Customer wants " . $_SESSION["unit"] . "<br>";
echo "This many times " . $_SESSION["frequency"] . "<br>";
?>
On first code, you have mix of PHP/JS...
Try put unit and frequency on same form, after submit.
And remember... TurnOn display_errors directive on php.ini
Session variables need to be assigned before the page loads. You cannot manipulate them with JavaScript. You should have the results once fully finalized submit to another page and then get the results using PHP on a new page load, or if you want to get into more complicated things submit them using ajax or something.
Your PHP should look more like this as well since you blended it with JavaScript originally.
include_once 'dbconnect.php';
if(isset($_POST['choose']))
{
$unit = $_POST['unit'];
$frequency = $_POST['frequency'];
// Set session variables
$_SESSION["unit"] = $unit;
$_SESSION["frequency"] = $frequency;
}
?>

Changing query variable, then executing it again

I am working on a PHP page that shows a table with query results. I want 2 buttons, with 'next' and 'previous', which change a variable used in this query:
SELECT les.lesuur, les.clustercode, les.lokaal, les.leraar, les.status
FROM les, zitin
WHERE zitin.leerlingnummer='$dimGebruiker'
AND zitin.clustercode=les.clustercode
AND les.dag='$huidigedag'
ORDER BY les.lesuur
$huidigedag is the one that should be changed. This is what I have in the beginning of the PHP code:
session_start();
if (!isset($_SESSION["huidigedag"])){
$_SESSION["huidigedag"] = 1;
}
$huidigedag = $_SESSION["huidigedag"];
Then, I added a link to the two buttons (arrow images):
<a href="volgende.php">
(volgende means next)
This is volgende.php:
<?php
$_SESSION["huidigedag"] = $_SESSION["huidigedag"] + 1;
header("location:leerlingrooster.php");
?>
However, when I click the button, nothing happens. I echo'd $huidigedag, and noticed it stayed on 1, without changing.
try to add session_start() to the beginning of volgende.php
I would change volgende.php to:
<?php
session_start();
$_SESSION["huidigedag"] = (!isset($_SESSION["huidigedag"])) ? 1 : ($_SESSION["huidigedag"] + 1);
header("location:leerlingrooster.php");
exit;
?>

Categories