php, form using the same page after submittion - php

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.

Related

How to pass variables in PHP with form action like solution to another PHP file after POST evaluation?

I have a form (user fills a textform, also upload a file), I am evaluating / validating the inputs. But after that how can I pass the post variablas as POST paramaters (like when a form used with submit button), to another PHP file ?
My sample code is:
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post" enctype="multipart/form-data">';
echo '<textarea name="identity" rows="5" cols="50"></textarea>';
echo "<input type='file' name='uploaded_file'>";
echo "<input type='submit' value='upload_file_test' name='submit'>";
echo "</form>";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["identity"])) {
$error_identity = "Empty identity, type something in the fields";
$correct_inputs=false;
} else {
$correct_inputs=true;
}
}
if($correct_inputs === TRUE){
pass $_POST["identity"], $_POST["file"] (including temp name, and other data) to index2.php
}
So how can I achive it like with something like form action to pass these to index2.php after $correct_inputs is TRUE ?

Why there's no output generated?

What wrong with my code? uniqid() is for generating a unique code and it will be stored to the name attribute then a condition is stated if it is clicked it will generate it's working.. Could some help me please with this one? Thanks in advance..
<html>
<form method="POST">
<?php
$attname = uniqid();
echo "<input type='submit' name='$attname' class='btn btn-success' value='Post to Peónline'/>";
echo $attname;
if(isset($_POST[$attname])){
echo 'its working';
}
?>
</form>
<html>
This isn't going to work.
When you refresh the page the $attname value will change. This will happen when you submit the form. So the actual name you're checking on will change and not be the same as the new $attname.
Put the following after your echo $attname; line:
print_r($_POST);
Also for this to work properly you'll need to nest the <input> tag in a <form> tag e.g.:
<form method="POST">
<input>...</input>
</form>
The $attname will change after page refresh.
You need to store that name somewhere.
Add another hidden element.
...
echo "<input type='hidden' name='elemname' value='<?php echo $attname;?>'/>";
...
And after submit,
if (isset($_POST['elemname'])) {
$elemname = $_POST['elemname'];
$val = isset($_POST[$elemname]) ? $_POST[$elemname] : '';
echo $val;
}

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,

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

PHP $_Post variables print but still give index errors?

Hey, I've got what has become an extremely frustrating problem with $_Post variables. I'll give examples of code rather than the actual segments to save time and confusion. On one page I'm doing this:
<? echo "<form name='form' action='page.php' method='post'>
<input type='hidden' name='slot' value=".$i.">
</form>";
?>
The $i is an index in a while loop (I'm echoing this simple form several times). The form itself is submitted with a bit a javascript.
All's well at this point, the form is submitted properly and takes me to another page, where I need to use that "slot" value to do some other junk. However, when I try to do this:
<? echo "<form name='another_form' action='another_page.php' method='post'>
<input type='hidden' name='slot_num' value=".$_POST['slot'].">
//SOME OTHER HIDDEN VARS
</form>";
?>
or this...
<? echo "<form name='another_form' action='another_page.php' method='post'>
<input type='hidden' name='slot_num' value=";
echo $_POST['slot'];
echo ">
//SOME OTHER HIDDEN VARS
</form>";
?>
or this...
<? //TOP OF PAGE
$slots = $_POST['slot'];
?>
<? //FURTHER DOWN
<? echo "<form name='another_form' action='another_page.php' method='post'>
<input type='hidden' name='slot_num' value=".$slots.">
//SOME OTHER HIDDEN VARS
</form>";
?>
...all I get is an Undefined index: slot etc.. etc... error, and source of the php document just has blank space. Funny thing is, if I simply do this:
echo $_POST['slot'];
at the top of the page, it prints out the value from the previous page just fine, however, if I view the source, it still shows an Undefined index error instead of the value. I KNOW the value is getting passed because it prints, but I can't use it for anything else because if I try to include it in my php code, it just displays an error and gives a blank value!
I've also tried using $HTTP_POST_VARS['slots'] with the same result... I am at wits end after several hours of experimentation... any advice?
check for emptiness:
if(empty($_POST['foo'])) {
$foo = "default foo";
} else {
$foo = $_POST['foo'];
}
print "My foo is '$foo'";
Edit:
Based on your comments and posted code, you seem to be trying to echo $_POST['slot'] when you should be echoing $_POST['slots']... note the s at the end.
Since $_POST is a super global, it is available anywhere on your page, so your code should work.
I noticed that you mixed slot and slots as the index in you post (you wrote $HTTP_POST_VARS['slots'] as the last example and $_POST['slot'] everywhere else). Could that be the reason?
To check what $_POST looks like, try this right about where you want to print the hidden value (though it should work the same anywhere on your page):
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
Also, your slot isn't being echoed with quote marks around it, so it should be:
<?php echo "<form name='another_form' action='another_page.php' method='post'>
<input type='hidden' name='slot_num' value='".$_POST['slots']."'>
//SOME OTHER HIDDEN VARS
</form>";
?>
Well I can't see anything wrong apart from a few syntax problems... okay so first of all, can you post me your javascript so I can see that.
Now instead of what you are doing with that, try this code:
?> <form name="another_form" action="another_page.php" method="post">
<input type="hidden" name="slot_num" value="<?php echo isset($_REQUEST['slot'])?$_REQUEST['slot']:'not found'; ?>">
</form>
<?
I am not fully sure what is wrong but i don't think the problem is in the code you've posted. it's probably sitting elsewhere so keep sending through code.
Try replacing...
<? //TOP OF PAGE
$slots = $_POST['slot'];
?>
with..
<?php //TOP OF PAGE
isset($_POST['slot']) : $slots = $_POST['slot'] ? $slots = '';
?>
Best of luck, hope that helps!

Categories