Storing value used in POST form in a PHP variable - php

I'm using a POST form that transfers data from one PHP file to another.. no issues there. However, I'm trying to store session data into a PHP variable.
<?php
if(!isset($_SESSION['login_user']))
{
session_start();
echo "<form action='../account.php' method='post'>";
echo "<p><b>Username: </b><input id='uname' type='username' name='uname' align='middle'></p>";
echo "<p><b>Password: </b><input id='pword' type='password' name='pword' align='middle'></p>";
echo "<p><input type='Submit' style='width:15%'></p>";
echo "</form>";
}
?>
I need the "uname" value to be stored as $_SESSION['login_user'] upon clicking submit, but this shouldn't prevent POSTing to the next page. How can I handle this?

session_start() should be initialized before anything you do in php
in your account.php initialize the session :
<?php
session_start();
$_SESSION['login_user'] = $_POST['uname'];
//rest of the stuff
?>

In account.php, do following assignment:
$_SESSION['login_user'] = $_POST['uname'];

Related

How to save php form data for use it later

I have a simple html form along with some php codes in a index.php file,
and my question is: how can I save that form data and use them in a diffrent page?
Php code looks like this:
if(isset($_POST['submit'])){
//collect form data
$name = $_POST['name'];
$email = $_POST['email'];
}
HTML code looks like this:
<form action='' method='post'>
<p><label>Name</label><br><input type='text' name='name' value=''></p>
<p><label>Email</label><br><input type='text' name='email' value=''></p>
<p><input type='submit' name='submit' value='Submit'></p>
</form>
Simplest solution is save this data in session but this have a limitation to browser close time and it's only assigned to current browser session:
<?php
session_start();
if(isset($_POST['submit'])){
//collect form data
$_SESSION['name'] = $_POST['name'];
$_SESSION['email'] = $_POST['email'];
}
echo $_SESSION['name'];
echo $_SESSION['email'];
?>
For better solution read this solutions and their limitations:
Session - http://php.net/manual/en/reserved.variables.session.php
File - http://php.net/manual/en/ref.filesystem.php
Database - https://www.w3schools.com/php/php_mysql_intro.asp
you can save in session like below code
<?php
session start();
$_SESSION['postdata'] = $_POST;
?>
I don´t know if this is what you want, since you dont specify, but you could save it via cookies with javascript, and then capture it with php.
JAVASCRIPT
//Call this in the html
function Example(element){
var name = $(elemt).find('name').text();
document.cookie = escape('variable') + '=' + escape(name) + '' + '; path=/';
PHP
$name= $_COOKIE['variable']))

Using a variable across the pages in PHP [duplicate]

My website involves a user submitting data over several pages of forms. I can pass data submitted on one page straight to the next page, but how do I go about sending it to pages after that? Here's a very simplified version of what I'm doing.
Page 1:
<?php
echo "<form action='page2.php' method='post'>
Please enter your name: <input type='text' name='Name'/>
<input type='submit' value='Submit'/></form>";
?>
Page 2:
<?php
$name=$_POST["Name"];
echo "Hello $name!<br/>
<form action='page3.php' method='post'>
Please enter your request: <input type='text' name='Req'/>
<input type='submit' value='Submit'/></form>";
?>
Page 3:
<?php
echo "Thank you for your request, $name!";
?>
The final page is supposed to display the user's name, but obviously it won't work because I haven't passed that variable to the page. I can't have all data submitted on the same page for complicated reasons so I need to have everything split up. So how can I get this variable and others to carry over?
Use sessions:
session_start(); on every page
$_SESSION['name'] = $_POST['name'];
then on page3 you can echo $_SESSION['name']
You could store the data in a cookie on the user's client, which is abstracted into the concept of a session. See PHP session management.
if you don't want cookies or sessions:
use a hidden input field in second page and initialize the variable by posting it like:
page2----
$name=$_POST['name']; /// from page one
<form method="post" action="page3.php">
<input type="text" name="req">
<input type="hidden" name="holdname" value="<? echo "$name"?>">
////////you can start by making the field visible and see if it holds the value
</form>
page3----
$name=$_POST['holdname']; ////post the form in page 2
$req=$_POST['req']; ///// and the other field
echo "$name, Your name was successfully passed through 3 pages";
As mentioned by others, saving the data in SESSION is probably your best bet.
Alternatly you could add the data to a hidden field, to post it along:
page2:
<input type="hidden" name="username" value="<?php echo $name;?>"/>
page3
echo "hello $_POST['username'};
You can create sessions, and use posts. You could also use $_GET to get variables from the URL.
Remember, if you aren't using prepared statements, make sure you escape all user input...
Use SESSION variable or hidden input field
This is my workaround of this problem: instead of manually typing in hidden input fields, I just go foreach over $_POST:
foreach ($_POST as $key => $value) {
echo '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
}
Hope this helps those with lots of fields in $_POST :)

php seems not to receive values from forms (post and get)

I'm trying to create a login and logout system. Everything works fine until I try to send hidden value (at the end) to log out. User would "submit" hidden value "logout" but it seems that the value is not send. I tried already different to approach this problem but either I am always getting errors message (but the code works) or I'm not getting errors message but it does not work.
<section>
<h2>Zaloguj się do systemu</h2>
<?php
//$username;
//$password;
if(empty($_SESSION['userpass']) && empty($_POST['pass'])){
//create a log in form if no one is log in
echo "
<form method='post' action='./indexLogin.php'>
<table>
<tr>
<td>Urzytkownik:</td>
<td><input type='text' name='name'/></td>
</tr>
<tr>
<td>Hasło:</td>
<td><input type='password' name='pass'/></td>
</tr>
</table>
<input type='submit' value='Wyślij'>
</form>
"; //end of echo
}
else if(empty($_SESSION['userpass']) && !empty($_POST['pass'])){
//echo the user name and his password
$userName = $_POST['name'];
$password = $_POST['pass'];
echo "Nastąpiło poprawne zalogowanie do systemu";
//save user password to session
$_SESSION['username'] = $userName;
$_SESSION['userpass'] = $password;
}
//problem starts here
else{
if($_POST['logout'] == true){
session_destroy();
echo "Nastąpiło poprawne wylogowanie z systemu";
}
else{
echo "Jesteś zalogowany jako: ".$_SESSION['username'];
echo "
<form method='post' action='./indexLogin.php'>
Do you want to log out?<br/>
<input type='hidden' name='logout' value='true'>
<input type='submit' value='Wyloguj'>
</form>
";
}
}
?>
when I use this code I get no error message but it does not work
//problem starts here
else{
if(!empty($_POST['pass'])){
//confirmation that log out was successful
//$_POST['logout'];
session_destroy();
echo "Nastąpiło poprawne wylogowanie z systemu";
}
else{
//form to log out
echo "Jesteś zalogowany jako: ".$_SESSION['username'];
echo "
<form method='post' action='./indexLogin.php'>
Czy chesz się wylogować?<br/>
<input type='hidden' name='logout' value='1'>
<input type='submit' value='Wyloguj'>
</form>
";
}
}
what I did as was was that I replaced post method with get. And what I found was that even if the value was in url it still did not work! I seemed that it never receive any value so it uses the last else.
First thing to check is that you actually have PHP >= 4.1 . In older PHP $_GET and $_POST just non-existent.
Second thing to check is actually print_r contents of your $_REQUEST (it is combination of $_GET and $_POST and $_COOKIE) and see if some data actually makes it to your script.
Third: I have executed your script on my host and ended up in "else if" branch. Clearly there no issue with your script but issue with the way your host handles requests. Are you on shared host? Some shared hosts have superglobals switched off intentionally and then you need to use $GLOBALS["_POST"] instead of $_POST
And of course use session_start()
actually your code seems to work, but you should enable your session with
session_start();
before your code. I was then able to submit the login credentials and to logout.
Cheers,

I'm trying to use a textbox value as a session variable

I'm trying to use a textbox value as a session variable when the button is clicked, so far I have it working but it's hardcoded in, how do I get it to use the textbox value instead?
Here's the session code:
<?php
session_start();
$_SESSION['url'] = "url";
?>
Here's the textbox:
echo "<input type='text' id='starurl' value=''/>";
echo "<br><button onclick='save_a9({$row99['starID']})'>Approve</button><button onclick='save_d9({$row99['starID']})'>Disapprove</button><br>";
Here's the save_a9:
function save_a9(id) {
$.post('response6.php', {starID:id},
function(result) {
alert(result);
window.location.reload();
});
}
Is this what you mean? the value doesn't need a form, it just needs to go to another page to be used there
<?php
session_start();
if (isset($_POST['url']) {
$_SESSION['url'] = $_GET['url'];
}
?>
echo "<input type='text' id='starurl' value='" . htmlspecialchars($_SESSION['url'])"
When you are assigning the _SESSION url, you will need to use the posted variable to assign the string.
$_SESSION['url'] = $_GET['url'];
To do the opposite, and have the textbox show the value of the session, you would:
echo "<input type='text' id='starurl' value='" . htmlspecialchars($_SESSION['url']) . "'/>";
It is important to note that if you want the text box to actually do something, you will need to have the input box wrapped around a form tag.
The <form> tag tells the browser where the form starts and ends. You can add all kinds of HTML tags between the <form> and </form> tags. (thanks echoecho!)
If you are working RESTfully, GET should be used for requests where you are only getting data, and POST should be used for requests where you are making something happen.
Some examples:
GET the page showing a particular SO question
POST a comment
Click the "Add to cart" button and send a POST request.
(Thanks Skilldrick!)
The form & PHP file would look like this:
<?php
session_start();
if (isset($_POST['url']) {
$_SESSION['url'] = $_POST['url'];
}
echo '<form action="POST" method="?">';
echo "<input type='text' id='starurl' value='" . htmlspecialchars($_SESSION['url']) . "'/>";
echo '</form>';
You will notice when the form is updated, the session updates too. When you close your browser and open it again, you will see you old contents on the input box. (Press "enter" to save the input box without a submit button).
Simply use this one
//page1.php
<form action="page2.php" method="post">
<input type="text" name="session_value">
<input type="submit" name="set_session" value="Set Session">
</from>
//page2.php
<?php
if(isset($_POST['set_session'])){
session_start();
$_SESSION['url'] = $_POST['session_value'];
}
?>
For getting the value from your textbox, first modify your HTML as :
<input type='text' id='starurl' name='url' value=''/>
The textbox needs a name attribute which is used by the $_POST, $_GET or $_REQUEST superglobals.
Then depending upon your form submission method (GET or POST) :
$_SESSION['url'] = $_GET['url'] // Default method for form submission
$_SESSION['url'] = $_POST['url'] // For <form method="post">
$_SESSION['url'] = $_REQUEST['url'] // Works for both
EDIT :
Since you are using a button onclick event to set the session variable, you can use this (assuming you are using jQuery) :
Javascript:
$('button').click(function(){
var url = $('#starurl').val();
$('#sessionURLDiv').load('save_session_url.php?url='+url);
});
PHP: save_session_url.php :
<?php
session_start();
if ( isset ( $_GET['url'] ) ) {
$_SESSION['url'] = $_GET['url'];
}
?>
HTML :
Just add this div anywhere in the page.
<div id = "sessionURLDiv"></div>
I hope this helps.

php, form using the same page after submittion

I'm wondering what's the easiest way to make let's say a form with user/pass and submit button with php but after you submit it goes back to the same page instead of going to another php page.
I'm thinking of if/else statement but a bit confused how to set it after lots tries but still not getting the result wanted
weird I did all those you guys said before I posted..but...>.<"
let's say just something simple like this...
but I also want to set if nothing is entered then sumbit is clicked there'll be an error....should be something easy but I don't know why I can't seem to figure it out
<?php
function userPass()
{
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . ">";
echo "<input type='text' name='user' /><br/>";
echo "<input type='text' name='pass' /><br/>";
echo "<input type='submit' value='Login' />";
}
if(empty($_POST["user"]))
{
userPass();
}
if(!(empty($_POST["user"])))
{
if($_POST["user"] == "comp")
{
echo "Welcome comp";
}
else
{
echo "Wrong user";
}
}
?>
The other answers are right; you only need to send the user back around to your current page in the "action" property. You can test to see if they did so using "isset".
Something that I'm surprised hasn't been mentioned yet is that your input is not being sanitized, and you're setting yourself up for disaster. Huge injection vulnerability in your action attribute:
$_SERVER['PHP_SELF']
If you don't sanitize this, then someone can just modify the URL that they see and your poor PHP script won't know any better than to process that as your SELF constant.
In other words, you absolutely must use an htmlspecialchars() function to html-encode that parameter. With that, your action should look more like htmlspecialchars($_SERVER['PHP_SELF']).
if current page is index.php, use index.php in form tag as value of action.
like this:
<form action="index.php" method="post">
</form>
u can check for submitted form by putting:
if(isset($_POST)){
...
}
at top of page
Just use below syntax
<form method="post" action="">
You can check whether post is set using isset() method.
<?php function userPass() {
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . ">";
echo "<input type='text' name='user' /><br/>";
echo "<input type='text' name='pass' /><br/>";
echo "<input type='submit' value='Login' />"; }
if(empty($_POST["user"]))
{
userPass();
}
*if(!(empty($_POST["user"])))*
{
if($_POST["user"] == "comp")
{
echo "Welcome comp";
}
else
{
echo "Wrong user";
}
}
?>
This part of your code is wrong, you should type : if(!empty($_POST["user"]))
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
This is exactly how you work with your form to reload the page when click the submit button inside this form.
ADDITIONAL:
Add required to all input you wanted to be required or check if it's empty.
This is a code that I created to control learning the required input fields satisfy the requirements. when this is so, the data will be sent to the database. if it does not meet the requirements, there will be a message may be shown at the top of the page
<?php
if (!isset($_POST['submitform'])) {
}
else
{
$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['mobile'] = $_POST['mobile'];
$_SESSION['telephone'] = $_POST['telephone'];
$_SESSION['place'] = $_POST['place'];
$_SESSION['street'] = $_POST['street'];
$_SESSION['housenumber'] = $_POST['housenumber'];
$_SESSION['gender'] = $_POST['gender'];
if (empty($_POST['firstname']) or empty($_POST['lastname']) or empty($_POST['email']) or empty($_POST['mobile'])or empty($_POST['telephone']) or empty($_POST['place'])
or empty($_POST['street']) or empty($_POST['housenumber']) or !isset($_POST['gender']))
{
echo "Sending denied";
}
else
{
require 'database.php';
header('Location: succes.php');
} ?>
I hope this is helpful information for you
this code will help you
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
or you could just do this:
<form action="" method="post">
Thank you ....
You can define in the form submission:
<form method=get action=index.php >
You can also leave action out altogether, and it will automatically post/get to that same file.
I think that all have missed the actual question, i.e. if there is a way to stay in the same page after submitting a form. The answer is NO. Once you submit a form -- whether you use the POST or GET method, and of course assuming that you are using $_SERVER['PHP_SELF'] or empty action, etc. -- a new page is opened automatically. This holds at least for PHP. (I have tried a lot of different ways using XAMPP.) I don't now about other scripting languages.

Categories