I am attempting to create a basic login/registration for a website using PHP. The code below shows that I required config.php which I tested and it connects to my site smoothly. What happens is when I go to the page, and enter in values, no matter what I enter for email and password, it says they always match. When I try to output the values of email1 and email2, it outputs nothing. I think the form isn't collecting the data when you press submit. If anyone could see what I am doing wrong it would be so appreciated!
<?php
require('config.php');
if(isset($_POST['submit'])) {
$email1 = $POST['email1'];
$email2 = $POST['email2'];
$pass1 = $POST['pass1'];
$pass2 = $POST['pass2'];
if($email1 == $email2)
{
echo "Emails match.<br />";
if($pass1 == $pass2)
{
echo "Passwords match.<br />";
}
else
{
echo "Sorry, your passwords do not match.<br />";
exit();
}
}
else
{
echo "Sorry, your emails do not match.<br /><br />";
}
}
else {
$form = <<<EOT
<form action="register.php" method="POST">
First Name: <input type="text" name="name" /><br />
Last Name: <input type = "text" name = "lname" /><br />
User Name: <input type = "text" name = "uname" /><br />
Email: <input type = "text" name = "email1" /><br />
Confirm Email: <input type = "text" name = "email2" /><br />
Password: <input type = "password" name = "pass1" /><br />
Confirm Password: <input type = "password" name = "pass2" /><br />
<input type = "submit" value = "Register" name = "submit" />
</form>
EOT;
echo $form;
}
?>
The problem is that you've forgotten the underscores for all $POST's
Change them all to $_POST
It's a superglobal which 8 out of 9 of those require the underscore, unlike $GLOBALS
$GLOBALS <=== No underscore required for this one.
$_SERVER
$_GET
$_POST <=== Change them all to this.
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
Had error reporting been set/on, you would have been signaled of the error, and multiple times:
Notice: Undefined variable: POST in...
To enable it, you can add the following after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
N.B.: Error reporting should only be done in staging, and never production.
Sidenote:
Since you're obviously running the entire code from the same page, you can simply change action="register.php" to action="" if you want.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
If you use plain text as a password storage method, I'm afraid that it will just be a question of time before your site gets compromised.
Related
I am trying to create a form in php with an else/if statement that asks the user for their name and age. It greets them with a welcome message and their name, and then if their age is 16 or over, the statement echos "You are old enough to volunteer for our program." If the user is under the age of 16, the statement will echo "Sorry, try again when you are older. Here is my code:
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
$age = 'age';
if ($age>=16)
{
echo $_POST["you are old enough to volunteer for our program!"];
}
else {
echo $_POST["Sorry, try again when you're 16 or older."];
}
?>
The input form is shown correctly, but "Sorry, try again when you're 16 or older" already appears when I open the web page and when I put my name and age in there, the welcome message with the users name works correctly, but absolutely nothing happens with the age statement. It still just says "try again when you're older" no matter what age I put in. HELP :(
For starters you need to use $_POST["age"] and not age. Also you should check if you are using get or post using $_SERVER['REQUEST_METHOD'].
If ($_SERVER['REQUEST_METHOD'] == "POST") {
// HandleForm
} else {
// showForm
}
I am working on my first $_POST form. I have created a simple HTML form and used the post method and my action points to a php document. I want to do some validation with the php to make sure the passwords match and simple things like that. I guess I am not understanding how to make the form work for me because right now when I submit my form, all it does is show my php code on the next page. How do you get the php to actually check the values instead of just displaying the code? Here is what I have for my php file:
<?php
function validatePassword($pwd) {
//create array to store test information
$messages = [];
//test for at least 8 characters
if (strlen($pwd) < 8) {
$messages []= "Your Password Must Contain At Least 8 Characters!<br />";
}
//test for max length
if (strlen($pwd) > 16) {
$messages []= "Your Password is too long!<br />";
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Number! <br />";
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Capital Letter!<br />";
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Lowercase Letter!<br />";
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Special Character!<br />";
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
$messages []= "Your password cannot contain a space!<br />";
}
//password passed all tests
if (empty($messages)) {
return "Password is acceptable<br />";
}
//return the array
return implode("\n", $messages);
}
if ($pass1 != $pass2){
$msg = "Passwords do not match";
}
else{
$msg = "Password confirmed!";
}
validatePassword($pass1);
?>
Form code:
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name=newForm method=post action=formProcess.php>
UserName: <input type=text name=userName size=15 maxlength=15><br>
Password: <input type=password name=pass1 size=15><br>
Confirm Password: <input type=password name=pass2 size=15><br>
<p>
I agree to the terms and conditions.<br>
<input type=radio name=terms value=yes> Yes
<input type=radio name=terms value=no> No
<p>
Enter comments here:<br>
<textarea name=comments rows=6 cols=50 wrap=physical></textarea>
<p>
<input type=submit name=submitForm>
<input type=reset name resetForm>
</p>
</form>
</body>
</html>
By the way I know I can put the php in the HTML document, but I really want to attempt to do two seperate files and see how this works. Thanks for any help!
It seems you don't have a web server
Download xampp and place your php file in the htdocs folder of the server, then you should be able to see it on http://localhost
Don't forget to actually start your Apache server and make sure it has a green light and no errors. Usually Skype will block it because it uses its port, so be careful on that.
Ok, first let's make some valid HTML
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name="newForm" method="post" action="formProcess.php">UserName:
<input type="text" name="userName" size="15" maxlength="15">
<br>Password:
<input type="password" name="pass1" size="15">
<br>Confirm Password:
<input type="password" name="pass2" size="15">
<br>
<p>I agree to the terms and conditions.
<br>
<input type="radio" name="terms" value="yes">Yes
<input type="radio" name="terms" value="no">No
<p>Enter comments here:
<br>
<textarea name="comments" rows="6" cols="50" wrap="physical"></textarea>
<p>
<input type="submit" name="submitForm">
<input type="reset" name="resetForm">
</p>
</form>
</body>
</html>
Then in your formProcess.php file, delete everything and try something like
<?php
echo $_POST["userName"];
?>
If this doesn't print the value you submitted in your username field, then there is a problem with your server.
In order to run PHP pages you need to first install it with a web server.
If you're using windows you can try WAMP which bundles PHP with Apache and MySQL:
http://www.wampserver.com/en/
For Linux:
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu
For MAC:
https://www.mamp.info/en/
In PHP there are two type validation such javascript validation (Client side validation) and another is Php Validation such as (Server side Validation).
1- In java Script validation done on Client Machine.
2- In Server Side (PHP validation) Done On server.
Hey i have having a problem i just found working with session i am using at the moment firefox 23 but i have check that on some other browsers as well.
I have created a simple code where i have created a form and just opened a session and i have noticed that once i have submit the form and then click on "Go Back" to return to the page the info i have inserted is not saved on the browser.
Normally when you submit a form once you go back the data you have entered is saved and you can just edit the inputs and resent it but when i have used session_start() on the page that function stopped working.
Well i am guessing maybe the browser save the form data in sessions as well and once i use it in php it's somehow effect the normally way the browser work.
I hope someone know how i can fix that i know you are able to save sessions with html5 and javascript now but i would rather do that with php.
Attached below is the code i have been using:
<?php
session_start();
// store session data
$_SESSION['name']= "name";
?>
<form method="post" action="index.php">
<input type="text" name="email" placeholder="Email" /><br />
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The browser refilling the form is simply that, the browser. This is not something you should rely upon for form re-population.
Your PHP code does not attempt to refill the form by printing anything within the input value="" attributes.
Generally when a form is submitted a programmer will validate the submitted values, store them in some fashion (the session is fine) and if they need them to reappear on the form they will print those values back out like I described.
I think you want to put the CORRECT fields back into the form values and blank out the incorrect ones. You don't have to use sessions:
<?php // formx.php
// accept POST variables
$fld1 = isset($_POST['fld1']) ? $_POST['fld1'] : "";
$fld2 = isset($_POST['fld2']) ? $_POST['fld2'] : "";
// edit variables
$errmsg = "";
if (!$fld1 == "") { if($fld1 <> "1") { $errmsg .= "fld1 is not 1<br />\n"; $fld1 = ""; } }
if (!$fld2 == "") { if($fld2 <> "2") { $errmsg .= "fld2 is not 2<br />\n"; $fld2 = ""; } }
if ($errmsg == "") { $errmsg = "Values accepted"; }
// output form
$body = <<<EOD
<html>
<body>
<div>%s</div><!-- errmsg -->
<form name="formnm" action="formx.php" method="post">
Enter "1" <input type="text" name="fld1" value="%s" /><br />
Enter "2" <input type="text" name="fld2" value="%s" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
EOD;
printf($body, $errmsg, $fld1, $fld2);
?>
I already have this code figured out, but the entries a user submits with the submit button aren't going anywhere. Is there any way to fix this, or should I just use the $_POST method?
PHP code:
<?php
include ("dbroutine.php");
function register() {
$connect = db_connect;
if (!$connect)
{
die(mysql_error());
}
$select_db = mysql_select_db(securitzed, $connect);
if (!$select_db) {
die(mysql_error());
}
//Collecting info
$fname = $_REQUEST ['fname'];
$lname = $_REQUEST ['lname'];
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$email = $_REQUEST['email'];
//Here we will check do we have all inputs filled
if(empty($_REQUEST['username'])){
die("Please enter your username!<br>");
}
if(empty($_REQUEST['password'])){
die("Please enter your password!<br>");
}
if(empty($_REQUEST['email'])){
die("Please enter your email!");
}
//Let's check if this username is already in use
$user_check = mysql_query("SELECT username FROM members WHERE username = '".$_REQUEST
['username']."'");
$do_user_check = mysql_num_rows($user_check);
//Now if email is already in use
$email_check = mysql_query("SELECT email FROM members WHERE email= '".$_REQUEST['email']."'");
$do_email_check = mysql_num_rows($email_check);
//Now display errors
if($do_user_check > 0){
die("Username is already in use!<br>");
}
if($do_email_check > 0){
die("Email is already in use!");
}
//If everything is okay let's register this user
$insert = mysql_query("INSERT INTO members (username, password, email)
VALUES ('".$_REQUEST['username']."', '".$_REQUEST['password']."', '".$_REQUEST['email']."', '".$_REQUEST['fname']."', '".$_REQUEST['lname']."')");
if(!$insert){
die("There's little problem: ".mysql_error());
}
}
switch($act){
case "register";
register();
break;
}
HTML code:
<body>
<form method="post">
First Name: <input type="text" name="fname" value="" /> <br />
Last Name: <input type="text" name="lname" value="" /> <br />
E-mail: <input type="email" name="email" value="" /> <br />
Desired Username: <input type="text" name="username" value="" /> <br />
Password: <input type="password" name="password" value="" /> <br />
Confirm Password: <input type="password" name="passwordconf" value="" /> <br />
<input type="submit" value="Submit"/>
</form>
</body>
If I need to add anything, could anyone point it out, if not, I could also add some extra code if needed.
$_REQUEST contains: $_COOKIE, $_GET, and $_POST variables. if you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. I would use $_POST but by using this method you are vulnerable to SQL injections.
$_GET retrieves variables from the querystring, or your URL. $_POST retrieves variables from a POST method, such as (generally) forms. $_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET.
Fix
You have to specify the action in your form as below.
<form action="fetch_data.php" method="post">
<form action="URL">
URL - Where to send the form-data when the form is submitted.
Possible values:
An absolute URL - points to another web site (like
action="http://www.example.com/example.htm")
A relative URL - points to a file within a web site (like action="example.htm")
First, I advice you to read more about variables.
Second, $_REQUEST is a variable like $_POST, $_SESSION, $_GET and so on, which can be stored into your database. So, for your question, Yes you can use $_REQUEST to insert data in a MySQL database
HOWEVER, using it as a substitute for the $_POST variable is not secure at all and not a good practice. Take a look at this to see how the $_POST variable works.
Third, you are using mysql_* functions in your code. please consider using PDO or MYSQLI instead to prevent SQL INJECTION and secure your website better. In addition, MYSQL is dupricated in PHP 5.5 and up. take a look at this tutorial, it shows you how to use PDO instead of MYSQL.
Fourth, you should not be storing passwords directly to databases, you need some form of password hashing. read more about it here
Try using
$fname = $_POST ['fname'];
$lname = $_POST ['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
You could also do following to check request params
var_dump($_POST);
Use ACTION in your HTML form.
Sanitize the data as well from sql injection.
Check if data from $_REQUEST is not empty.
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />