Sending value from one page to another with php session [duplicate] - php

This question already has answers here:
how to pass value from one php page to another using session
(2 answers)
Closed 6 years ago.
Im using wordpress
I wanted to send the data that is collected by form in the first page to the next page I didn't find anything that can send array data to another page other than GET command, GET commands uses URL, The reason I'm not using this GET is the sending information includes price values that are calculated using entered information
I found this $_session seems ok to my case (If any others are available, please tell me), Used wp session manager plugin to use $_SESSION.
im using it like this,
if(!isset($_SESSION)){
session_start();}
if(isset($_GET['B2'])) {
$_SESSION["info"] = "user-form";
$_SESSION["weight"] = $weight;
$_SESSION["price"] = $weight;
buy_now(); }
The B2 is a buy now button
function buy_now(){
if(isset($_GET['B2'])) {
header("Location:".get_site_url()."/buy-now/");
}
if(!isset($_SESSION)){
session_start();}
echo $_SESSION["info"]."<br>";
echo $_SESSION["weight"]."<br>";
echo $_SESSION["price"]."<br>";
}
The weight and price are Undefined index, the info will display.
What is the problem here? and How can I send variables to another page?, I'm unable to find any solution for now. Please help with this... Thank you

whenever you are need to check the session is start of not you should not check ist with $_SESSION you need to check the session_id() is generated or not (check the post for check the session start Check if PHP session has already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_GET['B2'])) {
$_SESSION["info"] = "user-form";
$_SESSION["weight"] = $weight;
$_SESSION["price"] = $weight;
buy_now();
}

word press provide another method like
wp_cache_get /
wp_cache_set
which you can use as own CMS method for passing data from one page to another page by define expiry time as well.
wp_cache_set
wp_cache_get

I think you have to try POST method.
<form action="test.php" method="post">
<input type="text" name="my_value" value="value"/>
...
</form>
On next page
<?php echo $_POST['my_value'];?>
That's it.

Refer https://codex.wordpress.org/Class_Reference/WP_Object_Cache for detailed explanation and remember to delete / reset as per your use case else might be a problem.

Related

How to use PHP global variable for 2 functions?

I'm trying to create an interface where a workshop description can be updated on the server after it has been created by a user. There is a text field and a button that brings up the workshop by the number it was assigned. (This is also the name of the directory in the submissions/workshop# on the server). When I set the variable $workshopPath using this method, I want to be able to access this global variable when a text input is filled out with the string to update the title of the workshop. The $workshopPath is registering as an empty string in the 'updateTextItems' function, so it is writing the text file to the root directory instead of to the correct workshop directory. I thought I was correctly referencing the global variable within the functions, but this isn't working. I also tried using $GLOBALS['workshopPath'], but that isn't working either. Can someone help me figure out how to pass the variable to the second function? Thanks :-)
<?php
$workshopPath;
if (isset($_POST['gotoWorkshop'])) {
if (empty($_POST['numberInput'])) {
echo "Please enter a valid workshop number";
} else { //Assign the name variable form the posted field info if one was entered.
$workshopNumber = stripslashes($_POST['numberInput']);
global $workshopPath;
$workshopPath = "submissions/" . $workshopNumber . "/";
}
}
if (isset($_POST['updateTextItems'])) {
if ($_POST['titleInput']) {
//Assign the name variable form the posted field info if one was entered.
$titleInput = stripslashes($_POST['titleInput']);
}
if ($titleInput) {
global $workshopPath;
$titleFile = fopen($workshopPath . "title.txt", "w") or die("There was an error creating the title file.");
fwrite($titleFile, $titleInput);
fclose($titleFile);
}
}
?>
Do I understood you correct? The user fill in the a form for the workshop click submit and get an othewr form for the text? My guess is you sen to requests to the server. So $GLOBAL will not work for you. It only works per request and I think most time you do not realy need it. If you want to save some values across requests, you need a session when you start your session. After you have started your session with session_start() you can use $_SESSION[] to store and get your value

How to update a session var while remaining on the same page in PHP? [duplicate]

This question already has answers here:
How to use store and use session variables across pages?
(8 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
On my page, users have the option to select a client. When they select one, this selection will be set in $_SESSION['selectedClient']. A user may then choose to pick a different client which would have to overwrite the current $_SESSION['selectedClient']. So when I try to update $_SESSION['selectedClient'] it will show me that the session variable has updated. But when I reload the page it will show the previous/first selected client.
Here is the piece of code I currently have to try this:
if($_POST['clientEmail']){
$_SESSION['selectedClient'] = $_POST['clientEmail'];
echo '<script>document.location=\'\?p=home\';</script>';
}
The echo leads to the same PHP file in which I set session var and try to update the session var, which is needed in this case.
I've tried to unset $_SESSION['selectedClient'] before assigning a new post like:
if($_POST['clientEmail']){
unset($_SESSION['selectedClient']);
$_SESSION['selectedClient'] = $_POST['clientEmail'];
echo '<script>document.location=\'\?p=home\';</script>';
}
I haven't been able to find anything on google that could help me, which is why I decided to make a SO account and ask here. Feel free to ask if more information is needed.
EDIT:
When $_SESSION['selectedClient'] is set and I select a new client, the post contains the newly selected value/client. After refresh, post is empty and session is reverted back to the client which was selected before.
selecting new client:
_POST['clientEmail'] = >lol#lol.com<
_SESSION['selectedClient'] = >lol#lol.com<
after refresh:
_POST['clientEmail'] = ><
_SESSION['selectedClient'] = >login#login.com<
please make sure to use session_start in the beginning of file and use isset function to check if there is any POST data
session_start()
if(isset($_POST['clientEmail'])){
$_SESSION['selectedClient'] = $_POST['clientEmail'];
header("Location: .\?p=home");
exit(0);
}

Display Php Code in HTML

Check the following code. I want to display the send mail parameters like mail, subject and message in HTML page. Please let me know how can i display it in HTML
// send email notification
if (($ed['notify_email'] == 'true') && ($ed['notify_email_address'] != ''))
{
$email = $ed['notify_email_address'];
$template = event_notify_template('email',$ed,$ud,$od,$loc);
sendEmail($email, $template['subject'], $template['message'], true);
}
You can use PHP's echo or print methods to display variables.
<?php echo($myVariable); ?>
or
<?php print($myVariable); ?>
If you want to perform your sendmail action in one php page, then redirect to another and show the data, then you need some means of storing it between views.
if your sendmail is successful store a record of it in your database, and pass the key for that record to your next php page. In that one, query the data for that key, get the result and display it using echo or print.
Similar to above, but store the data in the user's session (not really advised), and display it on the next page using echo or print.
Don't store the data, but pass it along to your next page as GET key/value pairs (not really recommended either), access it in the $_GET[] array and display it using echo or print.
The best solution in your situation is option 1. Store the record, look it up when you need it and display it. It's more secure and you're not putting the user's data in session or passing along in the query string. Plus it gives you a historical record in your database of actions in your site.

How to make a webpage retain variables from form?

Sorry if I'm duplicating threads here, but I wasn't able to find an answer to this anywhere else on StackOverflow.
Basically what I'm trying to do is make a list in which variables entered in a form by a user can be kept. At the moment, I have the code which makes this possible, and functional, however the variables entered in the form only appear on the list after the user hits submit... As soon as I refresh the page or go to the page from somewhere else, the variables disappear. Is there any way I can stop this from happening?
Edit: here are the codes:
//Page 1
<?php
session_start();
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
echo "<a href='Page 2'>Link</a>";
$_SESSION['entries_unique_values'] = $entries_unique_values;
?>
//Page2
<?php
session_start();
$entries_unique_values = $_SESSION['entries_unique_values'];
foreach($entries_unique_values as $key => $value) {
$ValueReplace = $value;
echo "<br /><a href='http://example.com/members/?s=$ValueReplace'>" . $value . "</a><br/>";
}
?>
Your question is really quite vague. the answer depends on how much data you have to store, and fopr how long you need it to exsist.
By variable I assume you mean data the user has entered and that you want to put into a variable.
I also presume that the list of variables is created by php when the form is submitted.
Php will only create the variable list when the form is submitted as php is done entirely on the server, therefore you will not have or see the variables until the form is submitted.
if you wanted to be able to see the list as it is being created you could use javascript then once you have you php variables the javascript list isn't necesary.
each time you request a php page wheather it is the same one or not the server generates a totally new page, meaning all unhardcoded variables from previous pages will be lost unless you continually post the variables around the pages the server will have no memory of them.
You have a few viable options.
) keep passing the user created variables in POST or GET requests so each page has the necesary info to work with. Depending on the situation it might or might not be a good idea. If the data only needs to exsits for one or two pages then it is ok, but bad if you need the data to be accessable from any page on your web.
2.) start a session and store the variables in a session. Good if the data only needs to be around while the user is connected to the site. but will be lost if user close window or after a time.
3.) place a cookie. not a good idea but ok for simple data.
4.) create a mysql database and drop the variable info in there. great for permanent data. this is how i always complex user data.
just a few ideas for you to look into as it is difficult to see what you really mean. good luck.
use PHP session or store variable values in Cookies via JS or using PHP. It would be nice if you show your working codes :)
Your idea is fine, however you just need to add a little condition to your Page 1 that only set your SESSION values when POST is made, that way it will keep the values even if you refresh. Otherwise when you visit the page without a POST those values will be overwritten by blank values, which is what you are seeing now. You can modify it like
<?php
session_start();
if(isset($_POST["signup_username"]))
{
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
$_SESSION['entries_unique_values'] = $entries_unique_values;
}
echo "<a href='http://localhost/Calculator/form2.1.php'>Link</a>";
?>
You could use JavaScript and HTML5 local storage.

Php header('Location") error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I'm having some difficulty with my php coding.
I have 3 files, add.php, lib.php, and view.php
I created a simple form, and when the user clicks submit, it should direct them to the view.php where it will display the database. Now I'm having a couple issues I can't seem to resolve.
when the user clicks submit and the fields are blank or there is an error no entry should be made into the view page (or database)...however when I click submit a blank entry is made into the database. ALSO if i click "enter product" from the top menu bar anytime I click it, it causes a blank entry into the database. I can't figure out why that's happening.
My next issue is with the header('Location')
and my browser says:
"Warning: Cannot modify header information - headers already sent by (output started at lib.php:13) in add.php on line 16"
However if I click submit on my form it goes away.
Here is the code for the pages:
I truly apologize if the code is really messy.
Any help / advice / solution is greatly appreciated thank you.
And yes this was an assignment---it was due last week but since I couldn't finish it, it's not worth any marks anymore.
Your if statement if (empty($_POST)){ will always fail and the else will run, thus the empty db entries.
$_POST will always have something in it, even for empty text inputs. Each key will be set to an empty string.
To test for whether you should save data or not you'll need to validate all required form fields. Your code will probably look something like this. This is by no means complete or secure, but it'll point you in the right direction.
<?php
// store validation rules for required fields
$requiredFields = array(...);
// Store all validation errors here.
$errors = array();
foreach($requiredFields as $key=>$rule) {
if(empty($_POST[$key])) {
$errors[$key] = true;
}
else {
// you can perform more validation work on the value here.
}
}
if(count($errors) > 0) {
// form submit failure.
}
else {
// form submit success, save to db
}
You are sending output before setting the header, thus the specified headers are not sent.

Categories