Two part form validation in PHP - php

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.

Related

Php Repeatable region

So i got this code, at the moment it is repeating everything , and i just wanted it to repeat the echo, so i get all usernames from it, if i leave it as it is it will also repeat the form when i press a username. Every time i tried to ajust it, it just gave me syntax errors
<?php do { ?>
<?php
$username = $row_mensagens['username'];
$user = $row_mensagens['id'];
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form>
Introduz mensagem : <br>
<textarea name='message' rows='7' cols='60'></textarea>
<br><br>
<input type='submit' value="Send Message" />
</form>
<?php
} else {
echo "<p><a href='mensagens.php?user=$user'>$username</a></p>";
}
?>
<?php } while ($row_mensagens = mysql_fetch_assoc($mensagens)); ?>
that do { } while() will always repeat as many as the number of records come from database.
You can do it this way:
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form>
<input type="hidden" name="user" value="<?php echo $_GET['user']; ?>" /> <!-- hidden field so you can process to who -->
Introduz mensagem : <br>
<textarea name='message' rows='7' cols='60'></textarea>
<br>
<br>
<input type='submit' value="Send Message" />
</form>
<?php
} else {
do {
$username = $row_mensagens['username'];
$user = $row_mensagens['id'];
echo "<p><a href='mensagens.php?user=$user'>$username</a></p>";
} while ($row_mensagens = mysql_fetch_assoc($mensagens));
}
?>
Move do { inside else and show the form only if you have a $_GET['user']
I have also added for you a hidden field, so you know who to send message.
Hope you understand how this works. Documentation on Control Structures: do-while
I also suggest to make that form a post form, as by default it is a get form, and since you have a textarea you are more likely to bump into errors if the message is too long.
LE: Another suggestion, try to move to PDO or mysqli_* functions since mysql_* functions are considered deprecated as of PHP 5.5 and have some good chances to be removed.

when working with php sessions form input data not getting save

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);
?>

How set requirements for text input field (html/php) ?

In my php script i have this input field.
<input type="text" name="try" size="10" id="try" maxlength="5" >
What is the easy way to make i require 5 characters and show an error message if they are not only letters.
With HTML5 you can use the pattern attribute:
<input type="text" name="try" size="10" pattern="[A-Za-z]{5}" title="5 alphabetic characters exactly">
This will allow exactly 5 characters, which can only be uppercase or lowercase alphabetic characters.
You can probably do that in jQuery on the client side. You will also need to do it on the server side, since JavaScript can (and will) be bypassed by an attack vector. A regular expression like this will do the server-side validation in PHP.
$rgx = '/[A-Z]{5,}/i';
Combining the approach...
http://www.laprbass.com/RAY_temp_axxess.php?q=abcde
http://www.laprbass.com/RAY_temp_axxess.php?q=ab
http://www.laprbass.com/RAY_temp_axxess.php?q=abcdefg
<?php // RAY_temp_axxess.php
error_reporting(E_ALL);
// A REGEX FOR 5+ LETTERS
$rgx = '/^[A-Z]{5,}$/i';
if (isset($_GET['q']))
{
if (preg_match($rgx, $_GET['q']))
{
echo 'GOOD INPUT OF 5+ LETTERS IN ';
}
else
{
echo "VALIDATION OF {$_GET['q']} FAILED FOR REGEX: $rgx";
}
}
// CREATE THE FORM
$form = <<<ENDFORM
<form>
<input type="text" name="q" pattern="[A-Za-z]{5,}" title="At least 5 alphabetic characters" />
<input type="submit" />
</form>
ENDFORM;
echo $form;
<input type="text" pattern=".{5,}" required />
try this
Assuming the page submits to itself.
Quick and Dirty.
<?php
$errors = array();
if (isset($_POST['try']) & strlen($_POST['try']) != 5 & ctype_alpha( $_POST['try'] != true) {
$error['try'] = "This field must contains 5 characters and contain only a-z and A-Z";
// stop whatever you normally do if submitted.
}
?>
Later on the page where you show this field.
<?php if (isset($errors['try'])) { echo $errors['try']; } ?>
<input type="text" name="try" size="10" id="try" maxlength="5" >
validate your form before view like this and use strlen to check the length of input:
if(isset($_POST['mySubmit'])) {
if(strlen($_POST['try']) < 5) {
$error = "Too short";
}
else {
$valid = true;
//Do whathever you need when form is valid
}
}
else {
if(isset($error)) {
echo "<p>$error</p>";
}
//echo your form here
echo "<form method='post' action='thisPhpScript.php'>
<input type='text' name='try' size='10' id='try' maxlength='5' >
</form>";
}
Haven't tested this so might have syntax errors.

I want an error box to pop up, but it doesn't even tho the error does occur

i have made a webform, and i have a script for the handeling of this form (php) this script works fine, but i also made a javascript error checker, now when i try to get some php in that script, it somehow bugs, and doesn't check my errors, in javascript,
below you will find the code i wrote for the error handeling, i'm not finished yet, but i'm currently stuck, since i need to go to my database to check something, and the javascript error handler bugs there.
quick walktrough:
I myself have 0 karma for the purposes of testing this error handling.
i click submit, and even tho i haven't filled in my username,
it doesn't show an error. and brings me directly to the php handler wich does find errors.
Do you like the content on our website? Do you want to be a part of it? Want to earn more Karma?<br />
Do you have what it takes to be a content creator? Then sign up here!<br> <br>
<?php
function getUID()
{
global $user;
if ($user->uid)
{
$userID=$user->uid;
echo $userID;
}
else
{
header('Location: http://brokendiamond.org/?q=node/40');
}
}
function getUN()
{
global $user;
if ($user->uid)
{
$username=$user->name;
}
echo $username;
}
function getKarma()
{
include "php-scripts/DBConnection.php";
$con = getconnection();
mysql_select_db("brokendi_BD", $con);
$result = mysql_query("SELECT * FROM userpoints WHERE uid='getUID()'");
$row = mysql_fetch_array($result);
$currentkarma = (int)$row['points'];
echo $currentkarma;
}
?>
<script type="text/javascript">
function validateForm()
{
var name=document.forms["CCF"]["username"].value;
var karma = parseInt(<?php echo json_encode(getKarma()); ?>);
var errors = "";
if (name==null || name=="")
{
errors += "Error: The username field cannot be empty";
}
if (karma < 500)
{
errors += "Error: Not enough Karma, you need at least 500 karma to submit this form";
}
if (errors != "")
{
alert(errors);
return false;
}
}
</script>
<form name="CCF" action="php-scripts/sendmail.php" method="post" onsubmit="return validateForm()" >
Username: &nbsp
<input type="hidden" name="UserID" value="<?php getUID() ?>">
<input type="text" name="username" value="<?php getUN() ?>" /><br>
E-mail adress:
<input type="text" name="mail" /><br><br>
What type of 'Content Creator' do you want to become? <br />
<input type="radio" name="CCT" value="Blogger" /> Blogger<br />
<input type="radio" name="CCT" value="Livestreamer" /> Livestreamer<br> <br>
What's your motivation?<br />
<textarea name="motivation" cols="60" rows="6"></textarea><br><br>
Why should we pick you as content creator?<br />
<textarea name="whyshouldwe" cols="60" rows="6"></textarea><br><br>
Do you have some reference material?<br />
<textarea name="reference" cols="60" rows="6"></textarea><br><br>
<h3>Rules to content creation</h3>
<p>You can only submit this once every day, the other versions will not be read, and you will lose Karma for each submit.<br />
When u submit this form, we will examine your account, and we will take a close look to your reference material.<br>
<h4>For Livestreamers Only</h4>
If we think you have what it takes to be a livestreamer ( frequent hours required ) we will examine your stream, and your computer/internet potential.<br />
If that is good enough for the website, you'll become a content creator.<br>
<h4>For Bloggers</h4>
If we think you are blogging material for out website, you will become a content creator, once you are accepted onto the team we will track your progress.<br />
If however you neglect your power or publish inappropriate content, then we will have no choice but to remove you from our team and will revert you to a regular user account.<br><br>
<input name="Send" type="submit" id="art-button-wrapper" value="I donate 500 Karma, and want to become a 'Content Creator'!" />
</form>
I can't see what the problem is, or why it won't work because i'm not skilled enough yet in javascript.
Thanks in advance,
Jonathan

Is there something wrong with my form?

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'] : ''; ?>" />

Categories