I am currently attempting to create a simple test web page which takes in a user's input of their name through a form and then after the form is submitted, the page is refreshed and the page now ONLY displays "Hello NAME".
Now, after going to this specific URL, you are no longer able to enter the name again and you only see the "Hello NAME" phrase. Also, the page with the form and the final phrase must be reachable by the same URL - they must be the same page.
Any help would be greatly appreciated!
So from what I understand you want to get a value from $_GET or $_POST.
After it goes to the other url you can set the NAME set by the user on a $_SESSION variable, you just need to start the session at the start of the page session_start() and then add the name into the variable $_SESSION['name'] = $_POST['name'] or $_SESSION['name'] = $_GET['name']; depends on what you want to do or use. And don't forget about htmlentities() and strip_tags() to "sanitize" the variable or to make it more secure to use.
After that you should print something like
echo "Hello ". $_SESSION['name']; or anything like that.
Here's a very basic example of how to do that using a session and post/redirect/get.
<?php
session_start(); // be sure to start the session first
// **don't output anything before this**
// if the name has been added to the session, echo the hello message and exit the script
// (the form won't be displayed)
if (isset($_SESSION['name'])) {
echo 'Hello ' . $_SESSION['name'];
exit;
}
// if the name has been posted, save it to the session and redirect to the same page
// (the form won't be displayed)
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
header('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
// If neither of those things are true, go ahead and show the form.
?>
<form method="post">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
Using PHP Sessions is one solution, and another one that you can use is using the GET Parameters.
<form action="page2.php" method="get">
<input type="text" name="user_name">
<button type="submit">Submit</button>
</form>
In the example above, what the form will do is submit the entered value (from the user_name input) to access it on page2.php file (this is the form action attribute).
In your page2.php file, you can access the value from the form by using
<?php
/** $_GET['user_name'] is the name of your input in the form */
echo "Hello " . $_GET['user_name'];
?>
NOTE: $_GET parameters is not recommended when accessing sensitive data, as this value is displayed and can be edited by the end-user in the URL.
Related
It seems pretty simple but I can't find a good way to do it.
Say in the first page I create a variable
$myVariable = "Some text";
And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).
How can I achieve this?
Thanks!
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
GET and POST
You can add the variable in the link to the next page:
Page2
This will create a GET variable.
Another way is to include a hidden field in a form that submits to page two:
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on page two:
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.
The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.
Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence regName and regValue:
Create your first page, call it set_reg.php:
<?php
session_start();
$_SESSION['regName'] = $regValue;
?>
<form method="get" action="get_reg.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
Create your second page, call it get_reg.php:
<?php
session_start();
$regValue = $_GET['regName'];
echo "Your registration is: ".$regValue.".";
?>
<p>Back to set_reg.php
Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.
Passing data in the request
You could either embed it as a hidden field in your form, or add it your forms action URL
echo '<input type="hidden" name="myVariable" value="'.
htmlentities($myVariable).'">';
or
echo '<form method="POST" action="Page2.php?myVariable='.
urlencode($myVariable).'">";
Note this also illustrates the use of htmlentities and urlencode when passing data around.
Passing data in the session
If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.
Security
Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?
As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!
There are three method to pass value in php.
By post
By get
By making session variable
These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-
$a=$_POST['field-name'];
If we require the value of variable on more than one page than we can use session variable as:-
$a=$_SESSION['field-name];
Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page
session_start();
GET method are generally used to print data on same page which used to take input from user. Its syntax is as:
$a=$_GET['field-name'];
POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST">
<button>
<input type="hidden" name="x">
</button>
</form>`
page 2
if(isset($_POST['x'])) {
$new_value=$_GET['variable_name'];
}
It works.
Send data throw URL, without form.
$upit = "SELECT * FROM usluga";
$data = $mysql->query($upit);
while ($row = mysqli_fetch_object($data))
{
echo "<a href='"."index.php?tretmanId=$row->tretman_id"."'>$row->naziv</a>";
echo "<br><br>";
}
and you can get this value on the target page with "$_GET['name from URL']", like this
$TrermanIdFromUrl = $_GET['tretmanId'];
You can for example call the page you want by including variables in the url:
header("Location: ../signup.php?newpwd=passwordupdated");
And on your signup.php page, you would have
if (isset($_GET['newpwd']) && $_GET['newpwd'] == "passwordupdated") {
//code here
}
Guys I have an external php file and its code is
session_start();
$_SESSION['test'] = $_POST['click'];
$query= "SELECT * FROM software where id='".$_SESSION['test']."' ";
$result=mysqli_query($con, $query);
$row=mysqli_fetch_array($result);`
on my index page I have
<form method="POST">
aaaa
<input name="click" type="submit" value="2">
</form>
<?php print_r($row);?>
and it works completely fine. But on another page of my site called exten.php I have
<?php print_r($row); ?>
which dosen't work if i direct user here onclick of link on second line of index
If your
<?php print_r($row);?>
is the only PHP code in your exten.php, it won't display anything because the $row variable that is set in your index page is not reachable.
If I get it well, you want to display the result of the click action on the button on a second page, named exten.php. If so, the action attribute on the form tag must be set.
<form action="exten.php" method="POST">
But if you want to display the value of what you have put in session (the variable test), the you have to start the session and then call your variable.
session_start();
echo $_SESSION['test'];
That is true for any pages.
Not sure why you put the value of a form input into session and then put this session variable in your query but in any case, you should sanitize your input values before using them in a SQL query. For example:
$test = filter_var($_SESSION['test'], FILTER_SANITIZE_STRING);
So when the user clicks submit, I would like it to take the form inputs and permanently save them to a variable. I'm not to sure how this could be done, but I am aware of this method, but it doesn't save it permanently.
<?php
$test = %_POST["example"];
?>
<form action="#" method="post">
Example Input: <input type="text" name="example"><br>
<input type="submit" name="submit"><br>
</form>
I then put
<?php echo $test ?>
which displayed my variable value, but as soon as the page is refreshed it's gone because of POST. How can I do something similar but when the page is refreshed it's still there?
I am open to other alternatives.
The problem is that $_POST variable lives only "per request", as you have already seen yourself when refreshing the page.
You can however use sessions to keep the variable alive as long as the session lives. Or you save the data to a database and fetch the data again when requesting the page.
Regarding sessions, you would do that like this:
<?php
session_start();
if (isset($_POST['example'])) {
$test = $_POST["example"];
$_SESSION['formData'] = $test;
}
if (isset($_SESSION['formData'])) {
echo $_SESSION['formData'];
}
<?php
For more information and a simple tutorial see: http://www.w3schools.com/php/php_sessions.asp
echo "Hello : ".$_SESSION['doc_username'];
//username sent from a different page by post method
$username = $_POST['username'];
echo "<p><strong>Showing Health Information for : </strong>";echo $username; "</p>";
if($_POST['submit'])
{
$height = mysql_real_escape_string($_POST['height']);
$weight = mysql_real_escape_string($_POST['weight']);
if($height && $weight)
{
require "dbc.php";
$query = mysql_query("UPDATE patient_info SET
height='$height',weight='$weight' WHERE username='$username'");
echo "Patient Data Saved!";
}
else
{
echo "All fields are required!";
}
The problem with this code is not in the mysql query. I have already checked it for syntax errors using phpcodechecker and there was none. There were more variables to be inserted into the database but height and weight will do for example. My problem is I am getting the username from a different page by POST method and I cannot save it in a way that it could be used by the "submit" value in this form to enable updating of that particular username. Because the username from the other form which $username cannot be referred to within the $_POST in this page, thus the username variable is blank when I click the submit button. How can I get a username sent from another page to this page by POST to be used in this form in the UPDATE query. The form does send the username to this page successfully which is proven when I can echo the username out. But it cannot be used by the form in this page. Please help as I am very new to PHP codes and I'm trying the best that I can.
On the initial page, add a hidden form element named "username" with the value you want to carry over into the form submission.
<input type="hidden" name="username" id="username" value="the.user.name">
You may store user name in session on request when it passed, or add to getparam of request or in hidden element of form:
<form action="procces.php?username={real_user_name}">
OR
<form>
<input type="hidden" name="username" id="username" value="{real_user_name}"/>
...
</form>
<input type="text" name="username" value="<?php echo $_POST['username']; ?>" />
The username in first page was transferred to another paged where you can edit it
As second page also contains a form so we also need to add username field int as when it will be posted the username will also be sent.
This had to be inserted into the 2nd form to retain the data sent from the previous in the previous page so that it can be used for the query in mysql.
First of all replace the line:
From:
if($_POST['submit'])
to:
if (isset($_POST['submit']))
If you are using a combobox then check that you have provided the name parameter in its markup like:
<select name="submit">
...
</select>
[EDIT]
After analyzing the code it is found that the HTML markup
was written after form element. I think this is the issue. Rest
appears to be Ok.
Hope this will solve the issue.
You may the user name in the session (supposed you have one, if not, you seriously should anyway):
Populating a form field like #tslocum suggested also needs to get the user name from somewhere. This is a quite common solution, but where does the user name come from?
There might be some time between submitting the name and rendering the current page, so as this is stateless but you need a state (State "we have a given username already") within that page during rendering and processing, take a look at $_SESSION global variable.
my approach:
Post 1:
....
$_SESSION['currentUser'] = $_POST['username'];
// you need some checks over here, don't use
// that as typed here, left out just for clearness.
... some time
Post 2:
...
$username = $_SESSION['currentUser'];
// again some checks over here!
read about $_SESSION in the php manuals.
It seems pretty simple but I can't find a good way to do it.
Say in the first page I create a variable
$myVariable = "Some text";
And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).
How can I achieve this?
Thanks!
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
GET and POST
You can add the variable in the link to the next page:
Page2
This will create a GET variable.
Another way is to include a hidden field in a form that submits to page two:
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on page two:
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.
The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.
Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence regName and regValue:
Create your first page, call it set_reg.php:
<?php
session_start();
$_SESSION['regName'] = $regValue;
?>
<form method="get" action="get_reg.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
Create your second page, call it get_reg.php:
<?php
session_start();
$regValue = $_GET['regName'];
echo "Your registration is: ".$regValue.".";
?>
<p>Back to set_reg.php
Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.
Passing data in the request
You could either embed it as a hidden field in your form, or add it your forms action URL
echo '<input type="hidden" name="myVariable" value="'.
htmlentities($myVariable).'">';
or
echo '<form method="POST" action="Page2.php?myVariable='.
urlencode($myVariable).'">";
Note this also illustrates the use of htmlentities and urlencode when passing data around.
Passing data in the session
If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.
Security
Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?
As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!
There are three method to pass value in php.
By post
By get
By making session variable
These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-
$a=$_POST['field-name'];
If we require the value of variable on more than one page than we can use session variable as:-
$a=$_SESSION['field-name];
Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page
session_start();
GET method are generally used to print data on same page which used to take input from user. Its syntax is as:
$a=$_GET['field-name'];
POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST">
<button>
<input type="hidden" name="x">
</button>
</form>`
page 2
if(isset($_POST['x'])) {
$new_value=$_GET['variable_name'];
}
It works.
Send data throw URL, without form.
$upit = "SELECT * FROM usluga";
$data = $mysql->query($upit);
while ($row = mysqli_fetch_object($data))
{
echo "<a href='"."index.php?tretmanId=$row->tretman_id"."'>$row->naziv</a>";
echo "<br><br>";
}
and you can get this value on the target page with "$_GET['name from URL']", like this
$TrermanIdFromUrl = $_GET['tretmanId'];
You can for example call the page you want by including variables in the url:
header("Location: ../signup.php?newpwd=passwordupdated");
And on your signup.php page, you would have
if (isset($_GET['newpwd']) && $_GET['newpwd'] == "passwordupdated") {
//code here
}