POST values from different Forms - php

I have form in my index.php that gets a value of name. In my action.php, I need to display the value using $_POST['name']. The name displays well when I directed into action.php However, I have another form in action.php that when I submit that form and refreshed action.php, the displayed name says an undefined index error for displaying name.
include('connect.php');
$name = $_POST['name'];
echo $name;
echo '<form method="get">';
//...
echo '<p><input type="submit" name="submit" value="GO" />';
echo '</form>';'

You are using the GET method while you should be using the POST method instead.
Change the following line:
echo '<form method="get">';
To:
echo '<form method="post">';

Check that $_POST['name'] is set using isset():
if(isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
}

For you to call $_POST['name'] from a form on a previous page, you will need to use form method = "GET" action = "targetpage.php"

use $_REQUEST["name"] it works for POST and GET Requests.
b.t.w. You should not echo Input data directly!! This can easily be used to do XSS Attacks. Use http://fr2.php.net/htmlentities or something like that before echoing a input directly to the browser! Otherwise a attacker could use something like alert('hax0rt'); as name ;)

Try this,
include('connect.php');
$name = isset($_POST['name']) ? $_POST['name'] : '';
echo $name;
echo '<form method="post">';
//...
echo '<input type="text" name="name"><br><p><input type="submit" name="submit" value="GO" />';
echo '</form>';'

Related

php wont redirect after form submission

I am trying to get my page to redirect after deleting a record from the database but it wont redirect. It is echoing out text and also deleting the record but it just reloads me on the same page with a form that no longer has information in it.
Here is the button im using
echo '<form>';
echo '<br /><br /><input style="cursor:pointer" class="button" type="submit" value="Delete Event" name="delete" id="delete" />';
echo '</form>';
Here is the PHP im using to delete the row from the DB
if (isset($_POST['delete'])){
$mysqli->query('DELETE FROM information WHERE id = '.intval($_GET['id']));
header('Location: index.php');
}
I have no idea whats wrong with it.
The header doesn't work, probably because there's already another one.
I suggest you to use a little part of Javascript:
if (isset($_POST['delete'])){
$mysqli->query('DELETE FROM information WHERE id = '.intval($_GET['id']));
echo "<script type='text/javascript'>window.location.href = 'index.php'</script>";
}
I assume that both the code snippets are present in a single PHP file. Then, your form will by default post to the same file using GET method.
Change your PHP code to look like this:-
<?php
if (isset($_GET['delete'])){
$mysqli->query('DELETE FROM information WHERE id ='.intval($_GET['id']));
header('Location: index.php');
}
echo '<form>';
echo '<br /><br /><input style="cursor:pointer" class="button" type="submit" value="Delete Event" name="delete" id="delete" />';
echo '</form>';
?>
Your form tag is completely empty. You check if $_POST["delete"] is set, but you haven't even specified the method of communication between your form and your PHP file on your form. Try changing your starting form tag to this:
<form method = "POST" action = "YOUR PHP FILE.php">
Your PHP file seems fine as long as index.php is on the same level as the form.
You can also redirect your page to somewhere else this way:
echo "<meta http-equiv="refresh" content="1;url=index.php"/>"
<form>
Delete id <input type = "text" name ="deleteid" id ="deleteid"/>
<input type ="submit" name = "submit" />
</form>
<?php
if (isset($_POST['submit'])){
$id = $_POST['deleteid'];
$query = "DELETE FROM information WHERE id = $id";
//rest Execute the query
header('Location: xyx.php');
}
<?

PHP recover data from Post

I have inside loop some fields for send inside form with other fields :
<?php
for($f=1;$f<=3;$f++)
{
?>
<input type="text" name="friend['email_<?php echo $f;?>']" value="<?php echo $_POST['friend']['email_'.$f.''];?>">
<?php
}
?>
When i send from form i need get the value of each field if no empty , i think the problem it´s in no recover the value send from the form , i don´t know if i writte right
Ony it´s that problem , thank´s , the best regards
I think the problem here is that you have single quotes around email_<?php echo $f; ?> - in POST data, these are not needed. So, you would have:
<form action="myPage.php" method="POST">
<?php for ($f=1;$f<=3;$f++) { ?>
<input type="text" name="friend[email_<?php echo $f; ?>]" value="<?php echo ... ?>">
<?php } ?>
<input type="submit">
</form>
PHP will parse POST data into associative arrays, so you will get back a 'friend' object in $_POST. You can access this like so:
<?php
$friends = isset($_POST['friend']) ? $_POST['friend'] : array();
print_r($friends);
?>
I'm not sure if i'm getting it right. You must send your form data in order to manipulate it. For example if you want to print all the form data:
Client Side:
<form action="boo.php" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit">
</form>
Server Side:
<?php
$name = "";
$age = "";
if( isset($_POST['name']) && isset($_POST['age']) )
{
$name = htmlspecialchars($_POST['name']);
$age = htmlspecialchars($_POST['age']);
}
echo 'Your name is ' . $name . ' and your age is ' . $age;
?>
If you are trying to retain the values even after invalid input you can just echo the input in value attribute of the input field.

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.

how to unset post array?

every time i am refreshing the page and i am getting the same value stored in the post array.
i want execution of echo statement only after submit and after refreshing no echo results..
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
From just a form, you won't be able to check if it was a refresh, or a first submit, regardless of using GET or POST method.
To ensure a single message, you need to:
a. redirect the user to somewhere else after you processed the request.
if(isset($_POST['submit'])) {
// process data
header("Location: new-url");
}
And display the message on the other URL.
b. set a cookie / session variable, which tells you the form was already processed.
if(isset($_POST['submit']) && !isset($_SESSION['form_processed'])) {
$_SESSION['form_processed'] = true;
}
This second approach will kill your form until the user closes the browser, so you should do something more complex - like storing another hidden field in the form, and storing that in the session.
If you submit a form and then refresh the resulting page, the browser will re-post the form (usually prompts first). That is why the POST data is always present.
An option would be to store a session variable and have it sent in the form, then check if it matches in the form processing code - to determine if it is a re-post or not.
Within the form:
<input type="hidden" name="time" value="<?php echo $time; ?>" />
In the PHP:
session_start();
if(isset($_POST['submit']))
{
if(isset($_SESSION['time']) && $_SESSION['time'] == $_POST['time'])
{
echo "User name : <b> $name </b>";
}
}
$time = $_SESSION['time'] = time();
Another option is to redirect after processing the post data:
if(isset($_POST['submit']))
{
...
...
header('Location: ' . basename($_SERVER['PHP_SELF']));
exit();
}
You need to maintain a state as to whether $name has already been displayed or not. The easiest way is probably to maintain that state in a browser cookie.
<?php
$nonce = $_COOKIE['nonce'];
$new_nonce = mt_rand();
setcookie('nonce', $new_nonce);
if(isset($_POST['submit']) && $_POST['nonce'] == $nonce)
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="nonce" value="<?php echo $new_nonce ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
Problems
you are polluting the user “session” with stale variable.
this will break if your user opens several windows (or tabs) to the same page. To fix this you would have to change the nonce cookie into an array of nonces, and update it accordingly.
if you want refresh page after submit use
<form method="get"
sure if your form hasn't a lot of data and also need to use $_GET instead of $_POST variable:)
correct way for you, but this logic is not good, need to refactor this script:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
unset($_POST['submit']);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>

Categories