PHP Validation

PHP validation is used to check whether the field is filled or not in the proper way by the user. There are two types of validation in PHP.
  • Client Side Validation:  Client side validation is performed on the client machine web browsers.
  • Server Side Validation: Server side validation is performed after submitting the data by user to check the validation on the server machine.
Following are the some validation rules for field
Field Validation Rules
Name Name should required letters and white-spaces
Website Website should required a valid URL.
Radio Radio must be selectable at least once.
Check Box Checkbox must be checkable at least once.
Email Email should required @ and.
Let us take an example of Form validation with require. Example
<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;} .divid{background-color:#9e9e9eb0;height: 290px;width: 170px;padding: 50px;margin:auto;}
</style>
</head>
<body>
<?php
// All the defined variables  set to empty values $nameErr = $emailErr= $commentErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr= "Name is required"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["comment"])) { $commentErr = "comment is required"; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
<h2 align="center">Form Validation Example</h2>
<div class="divid">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" placeholder="Enter your name...">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" placeholder="Enter your e-mail...">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<textarea name="comment" rows="4" cols="22" placeholder="Enter your comment          ..."></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br><hr>
<input type="submit" name="submit" value="Submit here">
</form>
</div>           
</body>
</html>
Note: The “$_SERVER[“PHP_SELF”]” variable  is a super global variable that  is used to returns the filename of the current executing script. It is always used by hackers. The “htmlspecialchars()”  function  is used to convert special characters to HTML entities( like: < and > with &lt; and &gt;). Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Output
<form method="post" action=         "test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

PHP Captcha  PHP CAPTCHA stands for Competently Automated Public Turing  test to tell Computers and Humans Apart. It is a type of challenge –response test that is used to determine whether user is human or not. Example of Arithmetic CAPTCHA
<?php
error_reporting(1);
$arr=range(99,9);
$brr=range(99,9);
$randa=array_rand($arr);
$randb=array_rand($brr);
$a=$arr[$randa];
$b=$brr[$randb];
$r=$a+$b;
$cap=$a."+".$b;
if(isset($_POST['b1'])){
if($_POST['t2']==$_POST['t3']){
echo '<center>'.'<font color="blue" size="5">'."CAPTCHA MATCH THANKU".'</font>'.'</center>';
}
else{
echo '<center>'.'<font color="red" size="5">'."CAPTCHA NOT MATCH".'</font>'.'</center>';
}
}
?>
<html>
<style>
.divid{background-color:#9e9e9eb0;height: 100px;width: 200px;padding: 50px;margin:auto;}
</style>
<body>
<div class="divid">
<form method="post">
<?php
error_reporting(1);
echo $cap."=";
?>
<input type="hidden" name="t3" value="<?php echo $r;?>">
<input type="text" name="t2" autofocus><br><br>
<input type="submit" name="b1" value="MATCH CAPTCHA">
</form>
</div>
</html>
Output PHP  Mail PHP mail() function is  used to send the mail  in PHP with various format like test message, html message and attachment message or file. Syntax:
mail( to, subject, message, headers, parameters );
Parameter Description
to The recipient's email address.
subject Subject of the email to be sent. This parameter cannot contain any newline characters(/n).
message It defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers It is optional and specify additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters It is used to pass additional parameter.
Sending Plain Text Emails The easy way to send an email with PHP, only we have to pass three parameter in mail() method. Let us take an example
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = 'rahul123@gmail';
$subject = 'Marriage Proposal';
$message = 'Hi Rahul Janu, will you marry me?';
$from = 'aprog@gmail.com';
// Sending email
if(mail($to, $subject, $message,$from)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
</body>
</html>
Output Your mail has been sent successfully PHP Mail with Attachment We can also send mail with attachment only we have to include header information. Let us consider an example.
<?php
$to = "abc@example.com";
$subject = "This is subject";
$message = "This is a text message.";
# Open a file
$file = fopen("/tmp/test.txt", "r" );//change your file location
if( $file == false )
{
echo "Error in opening file";
exit();
}
# Read the file into a variable
$size = filesize("/tmp/test.txt");
$content = fread( $file, $size);
# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content))
# Get a random 32 bit number using time() as seed.
$num = md5( time() );
# Define the main headers.
$header = "From:xyz@example.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$num\r\n";
$header .= "--$num\r\n";
# Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$num\r\n";
# Define the attachment section
$header .= "Content-Type:  multipart/mixed; ";
$header .= "name=\"test.txt\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"test.txt\"\r\n\n";
$header .= "$encoded_content\r\n";
$header .= "--$num--";
# Send email now
$result = mail ( $to, $subject, "", $header );
if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>

Related Topics

PHP chop() Function

PHP chop() Function The chop() function in PHP removes whitespaces or other predefined characters from the right end of the specified string. Syntax chop(str,charlist) Parameter str(required)- This parameter specifies the string to check. charlist(optional)- This parameter...

1 minute read.

PHP usort() Function

PHP usort() Function The usort() function in PHP sorts  array by values using a user-defined comparison function. Syntax usort ( array &$array , callable $value_compare_func ) array(required)- This parameter represents the input array. value_compare_func(required)- This parameter represents a string that describe a callable comparison function. The comparison...

1 minute read.

PHP arsort() function

PHP arsort() function The arsort() function in PHP sorts an array in the reverse order and maintains the index association Syntax arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to modify the behavior...

2 minutes read.

PHP list() Function

PHP list() Function The list() function in PHP sorts an array by key while maintaining the keys. Syntax list ( mixed $var1 [, mixed $... ] ) Parameter var1(required)- This parameter accepts variables separated by spaces. …(optional)- This parameter accepts a list of variables separated...

1 minute read.

PHP foreach Loop

PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax: foreach($array as $key => $value) { //Statement } $array = associative array. $key = array key. &value =...

2 minutes read.

PHP var_dump() Function

PHP var_dump() Function The var_dump() function in PHP is used to dump the information about a variable. It displays the structured information (arrays and objects) about one or more expressions. This function is also effective...

1 minute read.

PHP ord() Function

PHP ord() Function The ord() function in PHP converts the first byte of a string to a value between 0 and 255. This function interprets the binary value of the first byte of string as an...

1 minute read.

PHP quoted_printable_decode() Function

PHP quoted_printable_decode() Function The quote_printable_decode() function of PHP converts a quoted-printable string to an 8 bit string. It works similar to imap_qprint(), except this one does not require the IMAP module to work. Syntax quoted_printable_decode ( string $str ) Parameter str(required)- This parameter represents the...

1 minute read.

PHP array_diff_ukey() Function

The array_diff_ukey() function in PHP compares the keys from array1 against the keys from array2 and returns the difference containing all the entries from array1 that are not present in any of the other arrays. Syntax array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) Parameter array1(required)- This parameter signifies the...

1 minute read.

PHP strtolower() Function

The strtolower() function in PHP is used to convert a string to lowercase. This function is binary-safe. The related functions are as follows: strtoupper()lcfirst()ucfirst()ucwords() Syntax strtolower ( string $string ) Parameter string(required)- This parameter represents the input string. Return This function returns a string with all alphabetic...

1 minute read.

PHP metaphone() Function

PHP metaphone() Function The metaphone() function in PHP calculates the metaphone key (representing how a string sounds or pronounced) of a string. This function is used to text search and text matching or spelling...

1 minute read.

PHP setlocale() Function

PHP setlocale() Function The setlocale() function in PHP sets locale information(language, monetary, time and, other information specific for a geographical area.) Syntax setlocale ( int $category , array $locale ) Parameter category(required)- This parameter specified a named constant specifying the category of the functions affected...

1 minute read.

PHP Multidimensional Array

An array of arrays is called multidimensional array. It is used to store the data in a tabular form. It is represented in the form of matrix (row*column). Example: We can store...

2 minutes read.

PHP $ and $$ Variables

PHP $var variable is a normal variable that stores any value. PHP $$var variable is a reference variable that stores the value of$var inside it. Let us take an example. Example 1 <?php $x =...

1 minute read.

PHP settype() Function

PHP settype() Function The settype() function in PHP is used to set the type of variable var to type. Syntax settype ( mixed &$var , string $type ) Parameter var(required)- This parameter represents the variable being converted. type(required)- This parameter represents the type of variable that is needed.  The possible values of type are...

1 minute read.

PHP array_pop() Function

PHP array_pop() Function The array_pop() function in PHP pops or removes the last element from the array shortening the array by one element. Syntax array_pop ( array &$array ) Parameter array(required)- This parameter represents the input array to get the value...

1 minute read.

PHP rsort() Function

PHP rsort() Function The rsort () function in PHP is used to sort an array in reverse order i.e., highest to lowest. Syntax rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP substr_count() Function

PHP substr_count() Function The substr_count() function in PHP counts the number of times a substring occurs in the specified string. Syntax substr_count ( string $haystack , string $needle [, int $offset  [, int $length ]] ) Parameter haystack(required)- This parameter signifies the string to search in. needle (required)- This parameter represents the substring to search...

1 minute read.

PHP array_diff_key () Function

PHP array_diff_key () Function The array_diff_key () Function in PHP compares the keys from array1 against the keys from arrays. It returns an array containing all the entries from array1 whose keys are absent from all other arrays. This function is like array_diff () except that...

1 minute read.

PHP htmlspecialchars() Function

PHP htmlspecialchars() Function The htmlspecialchars() function in PHP converts some special predefined characters to HTML entities. The special predefined characters are as follows: & (ampersand) OR &amp;" (double quote) OR &quot;' (single quote) OR &#039;<...

2 minutes read.