Autoincrement url for anchor link - php

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'.'';?>

Related

How to access increment value of session on same page in php

How to access the incremented value of session on the same page where we have defined the initial value of session, I am using this method for incrementation of value but on another page
<?php
$_SESSION['indexValue'] = 1;
?>
This is my test.php page where i have decrelaed the inital value of session.
<?php
$Incrementvalue = $_SESSION['indexValue'];
$counter = (int)$Incrementvalue;
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
echo "$_SESSION['indexValue']";
?>
This is my getdata.php page where I have implmented the increment value function. Now i have to pass this increment value of Session again on test.php page . How can I perform this?
your code seems not to be thought off
first of all, you need to call session_start() at beginning
then you can access everyewhere your $_SESSION variable (if you call session_start() before)
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
this seems useless
$_SESSION['indexValue']++;
is enough
First of all there are few errors in code like
if ($counter=$counter) should be if ($counter == $counter)
And
echo "$_SESSION['indexValue']" should be echo $_SESSION['indexValue'].
Now answer to your question is that session is accessible anywhere throughout the project/application. So you need not to pass it , just access it as $_SESSION['indexValue'].

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

Incrementing the value of the post by every repeated form submission

I have a form sender which is posting a value of 6 to another form receiver. What I'm trying to achieve is store the posted value from sender into a variable in the receiverthen increment the variable it every time the sender posts. Then print the updated variable
This is what I have tried to do
$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;
Im getting the result as 12. But what I want is
After first post result = 12
After second post result = 18
On and on...
NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
$_SESSION['lastLimit'] = 0;
}
if(!empty($_POST)) {
$_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
$postedValue = $_POST['val'] + $_SESSION['lastLimit'];
echo $postedValue;
}
Because the web is stateless i.e. scripts do not remember anything that happened the last time a page/form was executed the receiver script does not remember anything from the last time it was run.
But dont panic, there is a way. Its called a SESSION and you can store data in the session which will then be available the next time this user connects to your site. In PHP you use it like this. The session is linked to this specific connection to a specific user.
receiver.php
<?php
// must be run at top of script, before any output is sent to the new form
session_start();
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
if ( isset($_SESSION['limit'] ){
// increment the limit
$_SESSION['limit'] += (int)$_POST['val'];
} else {
// initialize the limit
$_SESSION['limit'] = (int)$_POST['val'];
}
echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
// something is not right
// direct this user to some basic page like the homepage or a login
header('Location: index.php');
}
You need an intermediate layer to store the value.
Available options:
1) Global static value
2) session
3) file
4) database
I would recommend global value or session, as they data you want to store isn't that huge and would meet the requirements easily.
I would not write the syntax to store it in session as a number of people have already mentioned it. I just wanted to clarify the problem scenario and possible solutions.
You can store $limti into global varibale .
global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;

Pass $_GET variable to the next page

Right now im trying to code read other codes and make it work, because some of the projects that i have are made by other developers and i really have to learn reading other code, I already made this one work but the problem is when i try to incorporate this pagination code to a $_GET variable an error occur, when it load the first page everything thing is smooth but when i click the other pages the $_GET variable dies. i already found a code in the site but i can't really get how to incorporate it with the other code.
here is the code that "MIGHT" solve the problem solving pagination $_GET
printf('Next',$targetpage,http_build_query(array('page' => 2) + $_GET));
here is the part of the code that make the link 1 2 3 4. . . and so on
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1?srId=$srdd'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage?srId=$srdd'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x?srId=$srdd'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage?srId=$srdd'>></a> ";
// echo forward link for lastpage
//echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages?srId=$srdd'>>></a> ";
printf("<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages?srId=$srdd'>>></a>");
} // end if
/****** end build pagination links ******/
?>
I already figured it out guys I saw lots for this problem on the web and also some on the forum here's how to solve it
<?php
session_start();
// store session data
if (isset($_GET["srId"]))
{
$_SESSION['variable']=$_GET["srId"];
$srdd = $_SESSION['variable'];
}
else
{
$srdd = $_SESSION['variable'];
$tableName = $srdd."r";
}
?>
thanks for your response guys.
You will need to use either session variables or cookies to pass them one page to another.
The $_GET global array will be a NEW array for every new page, assuming you're sending a GET request and it can be seen in the URL.
In general, the web is stateless which means it will not remember what you do from one page to another UNLESS you use cookies, sessions or a database for persistence.
Design your links
Page 1 | 2 | 3 | 4
to have the information in the link so they are ready for the next page
Page 1 = http://url?page=1&page_limit=25
Page 2 = http://url?page=2&page_limit=25
...
Etc
If the paginated links are in this format, these variables will be in the $_GET array.
Try replacing
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1?srId=$srdd'><<</a> ";
with
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&srId=$srdd'><<</a> ";
After the initial '?' in a url, the following *'$_GET[]'* items should be separated from the preceeding one with an '&'. Note that your 'srId=$srdd' is preceeded by a '?'.
Example:
myurl.com?id=1234&page=help
Doing it this way will help you avoid having to store the information in the $_SESSION array, and keeps the URL secure.

Refreshing variable when clicking on link

Hello i got variable $offset. When user is viewing page - $offset should be equal to 0;
When he is clicking on link
Next
It should update the $offset by adding to it next's value.
So i wrote like this
$offset = $offset + $_GET['next'];
When i'm clicking on link first time it works, but the future clicks doesnt, because he dont remember $offset value. How should i write to do it right?
I would deplore using a session to store this. It is a waste of server resources.
$nextLot=3;
$offset=0;
if(!empty($_GET['offset']))
{
$offset=$_GET['offset'];
}
$offset+=$_GET['next'];
Next
This method saves some resources and simply checks the URL for all the info that is needed.
You can pass the $offset variable via $_SESSION.
So your code will look something like this:
$_SESSION['offset'] = $_SESSION['offset'] + $_GET['next'];
You can do this by using SESSION
<?php if(isset($_SESSION['next']) : ?>
Next
<?php else : ?>
Next
<?php endif; ?>
and for offset
$_SESSION['offset'] = isset($_SESSION['offset']) + $_GET['next'];

Categories