PHP - $_POST variables mixing with variables having the same name - php

On the same page I have
$hello = 'Hello!';
$_POST['hello'] = '123';
If I echo $hello, instead of getting 'Hello!' I get '123'.
How should I handle variables and $_POST variables with the same name?
This is an example of the real problem:
I have a signup form that looks like this (here's a minified sample of fields).
Each input field has a label and the string variable in the label has the same name as the input.
<form id="form1" action="post.php">
<span class="label"><?=$fullname?></span>
//$fullname='Please enter your name';
<input name="fullname" id="fullname" type="text">
<span class="label"><?=$email?></span>
//$email='Please enter your email';
<input name="email" id="email" type="text">
<input name="button1" id="button1" type="submit">
</form>
When I submit the form I post it to the same page and I display the values the user had filled out. Only that now, instead of $fullname displaying the value of the variable $fullname, it displays the value of $_POST['fullname']. Why does this happen?

probably you have register_globals turned on which is something that has been advised against for years already :) see here for details: http://php.net/manual/en/security.globals.php

The problem probably lies with register_globals in php's .ini file. Turn this off, restart php and it should be fixed.
Try this to check the setting at the moment of execution of the code:
echo ini_get("register_globals");

You must to set method="POST" attribute in form declaration. And may be you have register_globals option is enabled.

Check your php.ini for the register_globals setting. It is most likely set to on, you should turn it off.

Well if register_superglobals is off then you are doing similar in your script
like
foreach($_REQUEST as $key => $val) // or $_POST or $_GET
$$key = $val;

Related

Trying to test my post form (debugging)

I have a form, and I'm checking to see if it's submitting properly to post. This is my first foray into POST, so other than rudimentary research and tutorial stuff, I'm having a lot of problems. I wrote a simple script to see if my form is working properly at all. The HTML is clipped to only show you the form; I do have a validation and all that.
There is no naming conflict, whether in the filenames or those of the variables, so I assume it's a syntax error or just me being that guy with no knowledge of post whatsoever.
Here's the HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here's the post (named postest):
<?php
$name = $_POSTEST['name'];
$email = $_POSTEST['email'];
$help = $_POSTEST['help'];
echo {$name}, {$email}, {$help};
?>
This post was derived from this tutorial.
Also, I might as well ask: How would I go about submitting information to be (semi)permanently stored on a spreadsheet for my later perusal? However, this is a secondary question.
Part of your problem is that you are using a variable you're calling $_POSTEST when really what you want is the $_POST array. $_POST is a special reserved variable in PHP (and needs to be referenced using that exact syntax) which is:
An associative array of variables passed to the current script via the
HTTP POST method.
Reference: PHP Manual - http://php.net/manual/en/reserved.variables.post.php
So whatever input names and values you're passing into the PHP script come in via HTTP POST, and they'll be located in the $_POST array.
So using your example, it would be:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
echo {$name}, {$email}, {$help};
?>
There is not any $_POSTTEST array in php.
Use $_POST.

Why won't the results of my form POST to another .php?

I've got a real simple html form:
<form action="emailform.php" method=post>
<textarea name="emailBody"></textarea>
<p>If you want a reply :</p>
<input type="text" name="userEmail" id="emailSubmit" placeholder="Your Email">
<br>
<input type="submit" name="submit" class="submitButton">
</form>
And I'm just trying to get the inputs assigned to their respective variables in 'emailform.php', like this:
<?php
$email=$_REQUEST("userEmail");
print $email;
?>
As you can see I just tried it with one of the inputs, because I wasn't sure if the textarea works the same as a regular input, but even '$userEmail' doesn't seem to be getting the info as it doesn't print or echo anything.
I'm fairly new to this so this particular exercise is mostly for practice. In the end I don't want the submit button to redirect to another page, and I want the inputs emailed somewhere automatically, so if you can explain how to do that that would be great!
Your syntax is incorrect. You use brackets, not parentheses, to access array values.
$email=$_REQUEST("userEmail");
should be:
$email=$_REQUEST["userEmail"];
You could possibly try the following, if you are trying to assign what the end user has input into the field.
You have put:
$email = $_REQUEST("userEmail");
I personally believe this would not be the best way to do this as you are using the PHP POST method in your form therefore you should use the POST method in your PHP code also like this:
$email = $_POST['userEmail'];
$_REQUEST can be used for both $_POST and $_GET. But your are posting your information but if your are GETting the users input then simply use $_GET
Try that and tell me if it works.
After adding the missing the quotes on method="post" in your form tag, try this:
<?php
if (isset($_POST['submit'])) {
$email = $_POST['userEmail'];
print $email;
} else {
print "Oops, something went wrong."
}
?>

how to remove autocomplete with in a text box

I need to remove autocomplete in all the textbox with in my page
so I have given <input name="txt_username" id="txt_username" type="text" value="" autocomplete="off" /></dd></dl>
But it's not working does anyone know this?
Autocomplete, unless you're doing something crazy with AJAX, is a client-side thing and you can't always control it like that.
Since autocomplete works by caching your previous entries for a specific input text name, many banks randomly generate the input text name at each form page load but keep track of what is generated either somewhere else in a hidden input element or on the server side.
So instead of
<input name="txt_username" id="txt_username" type="text" value="" autocomplete="off" />
It might be something like
<input type="text" name="f6Lx571p" id="txt_username"/>
<input type="hidden" name="username_key" value="f6Lx571p" />
And the server-side code adjusted accordingly. For example, PHP code might have looked like:
<?php
$user = $_POST['txt_username'];
...
but it would have to be changed to something like:
<?php
$user = $_POST[$_POST['username_key']];
...
Its a bit annoying, but it works.
Autocomplete cannot be turned off, it's something from the browser, but I think this must help:<input type="password" name="password" readonly onfocus="this.removeAttribute('readonly')">
You can also try placing that autocomplete attribute on the form element.
<form id="myForm" autocomplete="off">
...
</form>
This will probably invalidate your HTML so you might want to consider adding this attribute dynamically with JavaScript.
Autocomplete cannot be turned off, it's something from the browser. What I do if I want to turn off autocomplete is the following:
Start a session with a field name and random number:
session_start();
$_SESSION['strUsername'] = "username_" . mt_rand(0, 1000000);
Now use this variable as the field's name:
name="' . $_SESSION['strUsername'] . '" id="txt_username" type="text" value="" autocomplete="off" /></dd></dl>
To check the value of the field simply use
$username = $_POST[$_SESSION['strUsername']];
Now, the name will be random everytime, so the browser will not recognize the field and will not give the autocompletion.

PHP $_POST not working? [duplicate]

This question already has answers here:
PHP POST not working
(10 answers)
Closed 8 years ago.
I have the simplest form possible and all I want to do is echo whatever is written in text box.
HTML:
<form action="" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
PHP:
if(isset($_POST['submit'])){
$test = $_POST['firstname'];
echo $test;
}
The problem is it's not working on my server (it works on another server). Does anyone has an idea what could be wrong? There are other forms on the server and are working fine.
I had something similar this evening which was driving me batty. Submitting a form was giving me the values in $_REQUEST but not in $_POST.
Eventually I noticed that there were actually two requests going through on the network tab in firebug; first a POST with a 301 response, then a GET with a 200 response.
Hunting about the interwebs it sounded like most people thought this was to do with mod_rewrite causing the POST request to redirect and thus change to a GET.
In my case it wasn't mod_rewrite to blame, it was something far simpler... my URL for the POST also contained a GET query string which was starting without a trailing slash on the URL. It was this causing apache to redirect.
Spot the difference...
Bad: http://blah.de.blah/my/path?key=value&otherkey=othervalue
Good: http://blah.de.blah/my/path/?key=value&otherkey=othervalue
The bottom one doesn't cause a redirect and gives me $_POST!
A few thing you could do:
Make sure that the "action" attribute on your form leads to the correct destination.
Try using $_REQUEST[] instead of $_POST, see if there is any change.
[Optional] Try including both a 'name' and an 'id' attribute e.g.
<input type="text" name="firstname" id="firstname">
If you are in a Linux environment, check that you have both Read/Write permissions to the file.
In addition, this link might also help.
EDIT:
You could also substitute
<code>if(isset($_POST['submit'])){</code>
with this:
<code>if($_SERVER['REQUEST_METHOD'] == "POST"){ </code>
This is always the best way of checking whether or not a form has been submitted
Dump the global variable to find out what you have in the page scope:
var_dump($GLOBALS);
This will tell you the "what" and "where" regarding the data on your page.
I also had this problem. The error was in the htaccess. If you have a rewrite rule that affects the action url, you will not able to read the POST variable.
To fix this adding, you have to add this rule to htaccess, at the beginning, to avoid to rewrite the url:
RewriteRule ^my_action.php - [PT]
Instead of using $_POST, use $_REQUEST:
HTML:
<form action="" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
PHP:
if(isset($_REQUEST['submit'])){
$test = $_REQUEST['firstname'];
echo $test;
}
Have you check your php.ini ?
I broken my post method once that I set post_max_size the same with upload_max_filesize.
I think that post_max_size must less than upload_max_filesize.
Tested with PHP 5.3.3 in RHEL 6.0
FYI:
$_POST in php 5.3.5 does not work
PHP POST not working
try doing var_dump($_GLOBALS).
A potential cause could be that there is a script running before yours which unsets the global variables. Such as:
unset($_REQUEST);
or even.
unset($GLOBALS);
This could be done via the auto_prepend_file option in the php.ini configuration.
try this
html code
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
php code:
if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;
}
There is nothing wrong with your code. The problem is not visible form here.
Check if after the submit, the script is called at all.
Have a look at what is submitted: var_dump($_REQUEST)
html file and php file both should reside in htdocs folder in c:\apache2 (if you use apache web server).
Open html file by typing http://"localhost/html_file_name.html"
Now enter Your data in fields.. Your code will run..
Try get instead for test reasons
<form action="#?name=test" method="GET">
<input type="text" name="firstname" />
<input type="submit" name="submit" value="Submit" />
</form>
and
if(isset($_GET)){
echo $_GET['name'] . '<br>';
echo $_GET['firstname'];
}

Storing form data with PHP Session

I am working on an HTML form whose data would be saved on a failed submit, or page refresh.
We are using a PHP Session to store this data, and we post the elements back when needed.
The issue is that it's not working. We need the form data to be preserved on a submit with errors, or page refresh. Currently on a failed submit, or page refresh, there is no data being stored in the session.
I'm fairly new to PHP, and most of this code is not mine, so go easy on me.
The PHP Sumbit code being used is:
Software: PHPMailer - PHP email class
Version: 5.0.2
Contact: via sourceforge.net support pages (also www.codeworxtech.com)
Info: http://phpmailer.sourceforge.net
Support: http://sourceforge.net/projects/phpmailer/
SESSION:
<?php
session_name("fancyform");
session_start();
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<div class="message-sent"><p>Message was sent successfully. Thank you! </p></div>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
FORM:
<form id="contact-form" name="contact-form" method="post" action="submit.php">
<p><input type="text" name="name" id="name" class="validate[required]" placeholder="Enter your first and last name here" value="<?=$_SESSION['post']['name']?>" /></p>
<p><input type="text" name="email" id="email" class="validate[required,custom[email]]" placeholder="Enter your email address here" value="<?=$_SESSION['post']['email']?>" /></p>
<p><input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?=$_SESSION['post']['phone']?>" /></p>
<p>
<select name="subject" id="subject">
<option>What event service are you primarily interested in?</option>
<option>Event Creation</option>
<option>Project Management</option>
<option>Promotion</option>
</select>
</p>
<textarea name="message" id="message" class="validate[required]" placeholder="Please include some details about your project or event..."><?=$_SESSION['post']['message']?> </textarea>
<input type="submit" value="" />
</form>
You are outputting $_SESSION['post']['form_element'] to your template but in the above PHP code there is no mention of setting that data. For this to work, you would have to loop through the $_POST array and assign each key pair to $_SESSION['post']
At that point you should be able to access the previously submitted form data from the session just as you have coded above.
add this to your submit.php:
session_start();
foreach ($_POST AS $key => $value) {
$_SESSION['post'][$key] = $value;
}
This will move all the data from $_POST to $_SESSION['post'] for future use in the template, and should be all you need to get it working.
HTTP is stateless, and data that is not submitted will not remain unless you use a client-side approach (webstorage, etc).
You need to parse the post variables and add them to the session super global, right now you are referencing $_SESSION['post']['phone'] which won't work as you expect.
// Assuming same file, this is session section
if (array_key_exists('submit', $_REQUEST)) {
if (array_key_exists('phone', $_REQUEST)) {
$_SESSION['phone'] = $_REQUEST['phone'];
}
}
// Form section
<?php $phone = (array_key_exists('phone', $_SESSION)) ? $_SESSION['phone'] : null;?>
<input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?php echo $phone ?>" />
Either you didn't include the code for submit.php or, if you did, the problem is clear: you're never setting the session values. In order to do that, you'd use
session_start();
// etc...
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['phone'] = $_POST['phone'];
// etc...
on submit.php and then the form page (presumably another page?) could then check if those values have been set
.. value="<?php if (isset($_SESSION['post']['name'])) echo $_SESSION['post']['name']; ?>" ..
I may be wrong, but I think you need to get the posted values from the form by using something like
if ($_POST['errStr']) {
$_SESSION['errStr'] = $POST['errStr'];
}
If i'm right its the way you're trying to access the variables after posting the form
If you look at the METHOD attribute of the form it set as post, so this should return the values you want to pass accross pages.
Maybe this isn't what you were asking though, i'm a little unclear what part the problem is with, i'm assuming its taking values from the form and getting them out on the next page.
If you want to do it when the page is refreshed/exited you'd probably need to use some javascript client side to try and catch it before the action happens.
Don't know if this is possible. PHP wont help you for that as its executed server-side, and the client wont submit anything (useful) to the server when they exit/reload, only the command to perform the action.
This'll probably require using javascript listeners, eg window.onclose (although apparently that doesn't work for safari or firefox 2), and within that an ajax xmlhttprequest to send the data to your server.
For failed submit (ie capture form with invalid data in?) its almost the same case as form that submit worked on. Just re-check the data on the other side when you're processing it.

Categories