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.
Related
I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!
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.
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.
I have a form which the user enters data eg first name and last name etc. I have PHP validation which checks for empty field. The problem is when the submit button is clicked, the whole form data is erased when a field is left empty.
I tried this method below.
<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"
id="UserName" size="20" />
But when the form loads for the first time, inside the text box is this
<br /><b>Notice</b>: Undefined index: UserName in ...... on line <b>477</b><br />
Is there a method to stop the form from being cleared? or to echo the data into the fields?
replace this :
value="<?php echo $_POST["UserName"]; ?>"
in your code with this :
<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
The issue here is that you're not checking whether $_POST["UserName"] is initialized, and when it is not, you'll throw the error. Check with isset:
<input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" />
Check if $_POST["UserName"] isset, Try this:
<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"
id="Givenname" size="20" />
I think you are using Reset button like this:
<input type="reset" />
Try this:
<input type="submit" />
If you are trying Second one then use required in every input like:
<input required type="text" />
Your form is not being cleared or erased. But you are loading a NEW page with a NEW form.
Your attempt to load the new form is a good one, but you need to change
<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName" id="UserName" size="20" />
into
<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" />
So remove the second value=" and the corresponding " which should have never been there. And check if the variable is available before trying to echo it.
In addition to doing this, you might also want to do client side validation in Javascript on top of the server side validation. (Never only do client side validation, by the way, as that can be fooled by end users.)
What you can do is to change your <form> tag into this:
<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
This will prevent the form from being sent to PHP when UserName is still empty. And thus prevent from the page being reloaded and the form being cleared.
PHP forms will often discard entered data upon error validation, even when echoing it in the input field caches the entry on successful submit, and it is understandable that erasing disallowed data would be the default behavior. However, it can be a real hardship to retype large amounts of text in a textarea, and its sudden vanishing may come as an unwelcome surprise to the user, especially when due to a simple reason such as an over-the-character-number limit.
Setting the $_POST['UserName'] value with the error validation should preserve the field input without allowing its process. The example uses a variable to cache the data and echo it into the input field.
Update: The script has been updated to include multiple submit buttons for the same form, as well as the option for a success message array.
Update: The script has been updated to include an exit() option as well as a textarea.
UserName and First Name allowed characters are defined and will
trigger an error with uppercase A-Z or special characters.
UserName uses the error array, while First Name uses exit() to stop
the script altogether.
Textbox allowances also will trigger an error with uppercase A-Z or
special characters, and use exit() to stop the script.
The form data will be preserved on error message, exit() page return, and successful send.
The form results are printed on successful send.
<?php
/* Define variables and set to empty values.*/
$username=$first_name=$textbox='';
/* If using non-array success variable, initialize it as a string:
$success='';
Otherwise, define as an array. */
/* Submit button is clicked, start validation.
Separate multiple submit buttons (for the same form) with || (|| = OR):
*/
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
// Define error and success messages as arrays to display in a list.
$error=array();
$success=array();
// Validate user input and error characters not lowercase a-z or 1-9.
if (!empty($_POST['UserName'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $username)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
$error[]='User Name can only contain lowercase a-z and 0-9.';
$username=$username;
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
$username=$username;
exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
*/
}
}
else {
$error[]="Please enter a User Name.";
}
if (!empty($_POST['first_name'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $first_name)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$first_name=$first_name;
exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
/*
$error[]='First Name may only contain lowercase a-z and 0-9.';
$first_name=$first_name;
*/
}
}
else {
$error[]="Please enter a First Name.";
}
if (!empty($_POST['textbox'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
/*
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$textbox=$textbox;
exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
/*
$error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
$textbox=$textbox;
*/
}
}
else {
$error[]="Please enter Textbox content.";
}
// If no errors, process data.
if (empty($error)) {
if (isset($_POST['submit_one'])) {
/* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
$_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
/* Post data or send email, and print success message.
The array is option. Do not define as an array or use[] to use as a simple variable. */
// Processing data here, for example posting to a database ...
$success[]="The submit_one Send Form request has been processed!";
}
if (isset($_POST['submit_two'])) {
$_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
// Processing data here, for example sending an email ...
$success[]="The submit_two Process Form request has been sent!";
}
}
/* If errors, show error message.
The exit() option ends the script at the validation check .*/
else {
$error[]="Please correct the errors and try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wrapper {margin: 2% auto; width: 500px;}
textarea {text-align:left;}
</style>
</head>
<body>
<div id="anchor" class="wrapper">
<div>
<form name="data_form" action="#anchor" method="post">
<table>
<tr>
<td colspan="2">
<label for="UserName">User Name</label>
<br>
<input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="first_name">First Name</label>
<br>
<input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="textbox">Textbox</label>
<textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit_one" id="submit_one" value="Send Form">
</td>
<td>
<input type="submit" name="submit_two" id="submit_two" value="Process Form">
</td>
</tr>
</table>
</form>
</div>
<div>
<?php
/* Print errors as a list or print success message.
Separate multiple submit buttons with ||. */
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
if (!empty($error)) {
echo '<h4>The form was not sent due to the following errors:</h4>
<ul>';
foreach ($error as $message) {echo '<li>'. $message . '</li>';
}
echo '</ul>';
}
/* Print success confirmations as a list for processed input. */
else {
echo '<h4>The form has been sent!</h4>
<ul>';
foreach ($success as $message) {echo '<li>'. $message . '</li>';}
/* If using a success variable without defining it as an array,
initialize it as a variable at the top of the script,
then print variable without <ul>s and foreach loop:
echo '<p>' . $success . '</p>';
*/
echo '</ul>
<h4>Processed Data:</h4>
<ul>
<li>User Name: ' . $username . '</li>
<li>First Name: ' . $first_name . '</li>
<li>Textbox: <br>' .
/* Replace $textbox new lines with <br> tags. */
nl2br($textbox) .
'</li>
</ul>';
}
/* Unset foreach loop data. */
unset($message);
}
?>
</div>
</div>
</body>
</html>
Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.