PHP setting session variables on button click - php

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;
}
?>

Related

How to pass PHP $_SESSION value to new page

Im trying to figure out how to use a php $_SESSION value. The situation is:
Main HTML site has an <iframe> that loads products.php
Within products.php a form submits and saves the two values below:
$_SESSION["subtotal"] = $_POST['SUBT'];
$_SESSION["tax"] = $_POST['TAX'];
These work well I can echo them no problem (within that page)
This page replaces products.php with confirmation.php
Once in the confirmation.php I am not able to grab the session values. I have tried the following:
<?php
session_start();
$_SESSION["subtotal"] = $_POST['SUBT'];
$_SESSION["tax"] = $_POST['TAX'];
echo $_SESSION["subtotal"];
echo $_SESSION["tax"];
echo $subtotal;
echo $tax;
?>
AND
$_SESSION["subtotal"] = $subtotal;
$_SESSION["tax"] = $tax;
echo $_SESSION["subtotal"];
echo $_SESSION["tax"];
echo $subtotal;
echo $tax;
?>
AND
$subtotal = $new_subtotal;
$tax = $new_tax;
echo $new_tax;
echo $new_subtotal;
?>
All have failed to see $_SESSION - Is the value getting lost with the <iframe> change?
I have used the following code on the products.php page to confirm the session were susecssfully created - They are:
echo $_SESSION["subtotal"]." stored in session <br />";
echo $_SESSION["tax"]." stored in session <br />";
NOTES:
Both confirmation & products.php are on the same server.
print_r($_SESSION); Returns BLANK array.
session_start() is at the very top of both pages
Use something like this:
products.php
<?php
session_start();
$_SESSION['myValue']=$_GET['YourFormElement'];
//or
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
I did that once by adding $_SESSION to url inside iframe and in file that is used in iframe I used that $_SESSION by $_GET.
I am not sure 100% but it should work as:
$session = $_SESSION['session'];
<iframe src="somePage.php?s=<?php echo $session; ?>"></iframe>
somePage.php
if(isset($_GET['s'])){
$session = $_GET['s'];
}

Maintaining PHP Session Variables

I would like to maintain 3 $_Session variables after login. My login modal submits to my index.php page and this seems to be the only place I can access the session variables I set when the user logs in. How do I pass these variables to the next page the user visits? I know I can use hidden inputs in forms but what if the brows the site using the menu? I would like to store a users session variables in a session include file but I have the same issue passing the values of the variables from page to page.
-Mike
File a.php:
<?php
session_start();
$_SESSION['saveme'] = 'from file A';
?>
File b.php:
<?php
session_start();
echo $_SESSION['saveme']; // if you visited a.php previously, you will see "from file A"
?>
Setting a session variable in any file makes it available anywhere else.
You can store you values in session on one page(index in your case as you mentioned) then later on you can get those values on any page if session in started on that page. Session store those value till same session alive.
code to set values in session:
<?php
// Start the session
session_start();
?>
<?php
// Set session variables
$_SESSION["xyz"] = "xyz";
$_SESSION["abc"] = "abc";
echo "Session variables are set.";
?>
Code to get session values:
<?php
// Echo session variables that were set on previous page
echo "value of xyz is " . $_SESSION["xyz"] . ".<br>";
echo "value of abc is " . $_SESSION["abc"] . ".";
?>
The form of your modal
<form action="index.php" method="post">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
</form>
Then you catch it in your index.php
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
// Check if user exists and password matches
$_SESSION['username'] = $_POST['username'];
$_SESSION['logintime'] = time();
$_SESSION['something'] = 'else';
}
In any other page you can use the values like
<?php
session_start();
if (isset($_SESSION['username'])) {
echo 'Welcome ' . $_SESSION['username'];
}
All who have provided answers thank you. This overlooked detail was all on me and though I have been out of the dev game for a while I should have known better.
My hosting service by default makes all file permissions read/write only...to access session variables I changed to read/write/execute and was successful.
Again thanks!

PHP cookies setting

I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.

how to unsave if page refreshed

I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).

Passing sessions variables through an iframe, php

First timer to the site, not an overly experienced php programmer here :)
I have a problem, i am using an iframe within a site which im attempting to use a session variable inside, firstly ive just been trying to display the session variable to make sure they are accessible from within the iframe:
echo "session of productcheck ".$_SESSION['productcheck']." ";
echo "session of productcheck1 ".$_SESSION['productcheck1']." ";
echo "session of productcheck2 ".$_SESSION['productcheck2']." ";
echo "session of productcheck3 ".$_SESSION['productcheck3']." ";
this just shows "session of product check" with nothing after each one, I set the session variable as such:
$_SESSION['productcheck'] = $productBox;
the $productBox is a GET from the URL:
echo " <iframe src=\"homeview.php?productBox=$product1\" name=\"FRAMENAME\" width=\"594\" height=\"450\" scrolling=\"No\" id=\"FRAMENAME\" allowautotransparency=\"true\" > </iframe >";
What's strange is if i just take the $productBox variable retrieved from the URL and use that then the code works, its only when i store it in a session variable that it gets confused. I want to retrieve a second $productBox and assign it to session var productcheck1 and so forth down the line. Unfortunately, i have to take one var in at a time, otherwise i could just pass all 4 products and not worry about the sessions.
Perhaps I'm making this far too complicated, any help would be much appreciated Thank you!!
You have to use session_start() in both scripts, the one setting the values (and presumably printing the <iframe>-element?) and the script that produces the contents for the iframe.
e.g. the "outer" script
<?php // test.php
session_start();
$_SESSION['productcheck'] = array();
$_SESSION['productcheck'][] = 'A';
$_SESSION['productcheck'][] = 'B';
$_SESSION['productcheck'][] = 'C';
session_write_close(); // optional
?>
<html>
<head><title>session test</title></head>
<body>
<div>session test</div>
<iframe src="test2.php" />
</body>
</html>
and the script for the iframe content
<?php // test2.php
session_start();
?>
<html>
<head><title>iframe session test</title></head>
<body>
<div>
<?php
if ( isset($_SESSION['productcheck']) && is_array($_SESSION['productcheck']) ) {
foreach( $_SESSION['productcheck'] as $pc ) {
echo $pc, "<br />\n";
}
}
?>
</div>
</body>
</html>
Not sure what's up with your session variables, but you can definitely pass all four variables through the url in your iframe. You just need to separate your key value pairs with an ampersand. So something like this:
file.php?key1=val1&key2=val2&key3=val3 and so on.
This is probably a better way than using session variables if your just trying to get data into that other file.

Categories