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 strrrev() Function

PHP strrrev () Function The strrev() function in PHP reverses a string. Syntax strrev ( string $string ) Parameter string(required)- This parameter represents the input string to be reversed. Return This function returns the reversed string. Example 1 Output Initial string: Hello...

1 minute read.

PHP array_push() Function

PHP array_push() Function The array_push() function in PHP pushes one or more elements onto the end of the array. This function increases the length of the array by the number of variables pushed. Syntax array_push ( array &$array, mixed& value [, mixed $... ]...

1 minute read.

PHP prev() Function

PHP prev() Function The prev() function in PHP rewinds or moves back the internal array pointer one place backward and returns the prev array value. It behaves like next() function, except that this function rewinds the...

1 minute read.

PHP break

What is Break in PHP? Inside the loop, the break statement is used to control the loop in preprocessor hypertext. PHP utilizes the break keyword to implement the break statement, which...

3 minutes read.

PHP is_array() Function

The is_array() Function in PHP is used to  find whether a variable is an array or not. It returns a Boolean value true if the parameter var is an array else it returns...

1 minute read.

PHP Forms

PHP form is used to take input from users, by using superglobals$_REQUEST, $_GET and $_POSTmethod. There are various request methods in PHP Get method Post method Put method Patch method Delete...

5 minutes 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 Constant

PHP constant is an identifier(name) for a simple value. The value does not change during the script. It starts with a letter or underscore not $ sign. The define()function is...

1 minute read.

PHP str_replace() Function

PHP str_replace() Function The str_replace() function in PHP replaces all occurrences of the search string with the specified replacement string. This function is case-sensitive. Syntax str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) Parameter search(required)- This parameter signifies the value to search. replace(required)-...

1 minute read.

PHP array_diff() Function

The array_diff () function in PHP compares array1 against other specified arrays and returns the values in array1 that are not present in any of the other arrays. Syntax array_diff(array$array1,array$array2[,array$...] ) Parameter array1(required)- This parameter signifies the input array to...

1 minute read.

PHP convert_cyr_string() Function

PHP convert_cyr_string() Function The convert_cyr_string() function in PHP converts from one Cyrillic character-set to another. The supported characters set are given below: k - koi8-rw - windows-1251i - iso8859-5a - x-cp866d - x-cp866m...

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.

PHP fprintf() Function

PHP fprintf() Function The fprintf() function in PHP outputs a formatted string. This function operates as printf() but accepts an array of arguments, rather than a variable number of arguments. Syntax vprintf ( string $format , array $args ) Parameter format(required)- This parameter specifies the string and how to...

4 minutes read.

PHP array_multisort() Function

PHP array_multisort () Function The array_multisort() function in PHP sorts multiple or multi-dimensional arrays at once. Syntax array_multisort ( array &$array1 [, mixed $array1_sort_order [, mixed $array1_sort_flags [, mixed $... ]]] ) Parameter array1(required)- This parameter specified the input array to sort. array1_sort_order(optional)- This parameter specifies the order (ascending or descending)...

1 minute read.

PHP get_defined_vars() Function

PHP get_defined_vars() Function The get_defined_vars() function in PHP returns an array of all defined variables. It returns a multidimensional array containing a list of all defined variables. Syntax get_defined_vars ( void ) Parameter NA Return This function returns a multidimensional array containing a list...

1 minute read.

PHP array_replace() Function

PHP array_replace() Function The array_replace() function in PHP replaces the elements from passed arrays into the first array with values having the same keys in each of the following arrays. Syntax array_replace ( array $array1 [, array $... ] ) Parameter array(required)- This parameter represents...

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 uksort() Function

PHP uksort() Function The uksort() function in PHP sorts an array by keys using a user-defined comparison function. Syntax uksort ( array &$array , callable $key_compare_func ) Parameter array(required)- This parameter represents the input array. key_compare_func(required)- This parameter represents a string that describe a callable comparison function....

1 minute read.

PHP asort() function

PHP asort() function The asort() function in PHP is used to sort an array while maintaining the index association. Syntax asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  array(required)- This parameter represents the input array to sort. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP array_diff_uassoc() Function

PHP array_diff_uassoc() Function The array_diff_uassoc () Function in PHP is used to compare the keys and values of two (or more) arrays and returns the differences (an array containing the entries from the first array that...

1 minute read.