PHP Functions
A PHP function is a block of statements that can be used repeatedly in a program. It is not executed when page is loaded, instead implemented when a function is called.
Function Syntax
Function function _name ()
{
Code to be executed;
}
Example
Function test()
{
Echo “hello”;
}
Test();
Function with arguments
Arguments or parameters are a piece of information, which is passed to function for executing the code. Functions can have any number of arguments, just separate them by comma.
Function test($fname)
{
Echo $fname;
}
Test(“janani”);
Default Argument Value
The default argument will be set, if a function is called without parameters.
Function test($fname=50)
{
Echo $fname;
}
Test();
Return value function
Return value function is used when a function has to return a value after code execution.
Function test ($a, $b)
{
Return $a+$b;
}
Echo Test(2,3);
HTML video Tag
The <video width=”300″ height=”150″> tag specifies video, such as a movie clip or other video streams.
There are 3 supported video formats for the <video> element: MP4, WebM, and Ogg
Normal Video:
<video width=”320″ height=”240″ controls>
<source src=”play.mp4″ type=”video/mp4″>
<source src=”play.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>
Autoplay Video:
<video controls autoplay>
<source src=”songs.mp4″ type=”video/mp4″>
Your browser does not support the video tag.
</video>
PHP Form Validation
<?php
// define variables and set to empty values
$nameError = $emailError= $genderError = $websiteError = “”;
$name = $email = $gender = $comment = $website = “”;
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
if (empty($_POST[“name”])) {
$nameError = “Name is required”;
} else {
$name = test_input($_POST[“name”]);
// check if name only contains letters and whitespace
if (!preg_match(“/^[a-zA-Z ]*$/”,$name)) {
$nameError = “Only letters and white space allowed”;
}
}
if (empty($_POST[“email”])) {
$emailError = “Email is required”;
} else {
$email = test_input($_POST[“email”]);
// check if e-mail address syntax is valid
if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”,$email)) {
$emailError = “Invalid email format”;
}
}
if (empty($_POST[“website”])) {
$website = “”;
} else {
$website = test_input($_POST[“website”]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match(“/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i”,$website)) {
$websiteError = “Invalid URL”;
}
}
if (empty($_POST[“comment”])) {
$comment = “”;
} else {
$comment = test_input($_POST[“comment”]);
}
if (empty($_POST[“gender”])) {
$genderError = “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>PHP Form Validation</h2>
<p><span class=”error”>* required field.</span></p>
<form method=”post” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>“>
Name: <input type=”text” name=”name”>
<span class=”error”>* <?php echo $nameError;?></span>
<br><br>
E-mail: <input type=”text” name=”email”>
<span class=”error”>* <?php echo $emailError;?></span>
<br><br>
Website: <input type=”text” name=”website”>
<span class=”error”><?php echo $websiteError;?></span>
<br><br>
Comment: <textarea name=”comment” rows=”5″ cols=”40″></textarea>
<br><br>
Gender:
<input type=”radio” name=”gender” value=”female”>Female
<input type=”radio” name=”gender” value=”male”>Male
<span class=”error”>* <?php echo $genderError;?></span>
<br><br>
<input type=”submit” name=”submit” value=”Submit”>
</form>
<?php
echo “<h2>Your Input:</h2>”;
echo $name;
echo “<br>”;
echo $email;
echo “<br>”;
echo $website;
echo “<br>”;
echo $comment;
echo “<br>”;
echo $gender;
?>
</body>
</html>
PHP Form Validation
* required field.
Your Input:
Name
Test@gmail.com
www.example.com
Test Comment
Female
Simple Capcha using php
Capcha Code:
Save this code as “capcha.php”
[php]
<?php
session_start();
$text = rand(10000,99999);
$_SESSION[“vercode”] = $text;
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
?>
[/php]
——————————————————————————————————
HTML:
<img src=”capcha.php” alt=”” align=”top” /> <input id=”vercode” class=”cap” name=”vercode” type=”text” align=”texttop” />
<div>
<input class=”sub” name=”subi” type=”submit” value=”Register” />
</div>
Must set session to use the capcha
PHP Code for the html page:
[php]
<?php if ($_POST[“vercode”] != $_SESSION[“vercode”])
{
header(“location:contact.php?ver”); //incorrect verification code }
?>
[/php]
Send an HTML Email Using PHP
PHP Mail Function:
The mail() function allows you to send emails directly from a script.
Syntax For E-mail:
mail($to,$subject,$message,$headers);
[php]
<?php
$to = "someone@example.com, someoneelse@example.com";
$subject = "HTML email ";
$message = "<table><tr><td>Congrats</tr></td></table>";
// Always set content-type when sending HTML email//Very Very Important headers</h4>
$headers = "MIME-Version: 1.0" . "\r\n";</h4>
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";// More headers</h4>
$headers .= ‘From: <webmaster@example.com>’ . "\r\n";
$headers .= ‘Cc: mymd@example.com’ . "\r\n";
mail($to,$subject,$message,$headers);
?>
[/php]
PHP Sessions
Starting a PHP Session
- The session_start() function must appear BEFORE the <html> tag:
[php]
<?php session_start(); ?>
<html>
<body>
</body>
</html>
[/php]
- The above code is used to register the user session in server.
Destroying a Session
[php]
<?php
session_destroy();
?>
[/php]
- The above code is used to destroy the complete session from the server.
NOTE : The session is very very important to save the current user information on the server. Using UID(user id), The server saves the user information on the server.
Hide/Show using JavaScript
To hide the Div : style=”display:none”;
To visible the Div : style=”display:block”;
[php]
<html><head><script type="text/javascript">
function showdiv()
{
if(document.getElementById(‘child’).checked)
{
document.getElementById(‘adu’).style.display = "block";
}
else
{
document.getElementById(‘adu’).style.display = "none";
}
if(document.getElementById(‘adult’).checked)
{
document.getElementById(‘adu’).style.display = "none";
}
}
</script>
</head>
<table border="0">
<tbody>
<tr>
<td>Member Type</td>
<td>
<input id="adult" onclick="showdiv();" type="radio" name="member" value="Adult" />
<input id="child" onclick="showdiv();" type="radio" name="member" value="Child" /></td>
</tr>
<div id="adu" style="display:none">
<tr><td>Name</td><td><input type="text" value=""></td></tr>
</div>
</tbody>
</table>
</html>
[/php]
Output:
When you Click the Adult , you will not see the text box below.
When you click the child, the below text box will be visible.
| Member Type | Adult Child |
| Name | * |
How to Upload a image from HTML form using PHP?
[php]
<?php
if(isset($_REQUEST[‘sub’]))
{
$fileType = $_FILES[‘img’][‘type’];
$fileSize = $_FILES[‘img’][‘size’];
if($fileSize/1024 > ‘2048’)
{
echo ‘Filesize is not correct it should be equal to 2 MB or less than 2 MB.’;
exit();
} //FileSize Checking
if($fileType != ‘image/png’ && $fileType != ‘image/gif’ && $fileType != ‘image/jpg’ && $fileType != ‘image/jpeg’ )
{
echo ‘Sorry this file type is not supported we accept only. Jpeg, Gif, PNG’;
exit();
} //file type checking ends here.
$upFile = ‘uploads/’.date(‘Y_m_d_H_i_s’).$_FILES[‘img’][‘name’];
if(is_uploaded_file($_FILES[‘img’][‘tmp_name’])) {
if(!move_uploaded_file($_FILES[‘img’][‘tmp_name’], $upFile)) {
echo ‘Problem could not move file to destination.’;
exit;
}
} else {
echo ‘Problem: Possible file upload attack. Filename: ‘;
echo $_FILES[‘img’][‘name’];
exit;
}
$img= $upFile;
} //File upload ends here.
}
?>
<html>
<body>
<h3>File Upload:</h3>
Select a file to upload:
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="img" size="50" />
<input type="submit" name="sub" value="Upload File" />
</form>
</body>
</html>
[/php]
File Upload:
Select a file to upload:
How To Use Jquery Mutliselect Dropdown
I am using http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
Samples here
Initially it seemed tough to get it working as a beginner, but eventually I managed to successfully get it to work.
Step 1:
Download the Jquery Code Or You Can Include it From CDN (Content Delievery Network)
For multiple select drop-down, We need to include the following resource,
Download links are
After including the above files your code will look like:
[php]
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../src/jquery.multiselect.js"></script>
[/php]
Step 2:
Use JavaScript Function to Trigger Multi-Select Event
[php]
<script>
$(document).ready(function(){
$("#check_list").multiselect();
});
</script>
[/php]
For customizing multi-select,We have to pass in a object with one or more options like header.height etc. For all available options Click Here
Step 3:
In <select> tag define multiple attribute for selecting multiple options and define name in array format as specified below.
Note that at the end of check_list in the <name>tag [] symbol is used,that denotes the array
[php]
<select name="check_list[]" id="check_list" multiple="multiple">
<option value="1"> Apple </option>
<option value="2"> Orange </option>
<option value="3"> Mango </option>
<option value="4"> Grapes </option>
<option value="5"> Strawberry </option>
</select>
[/php]
Step 4:
When you have embedded this multi-select dropdown in your form,
Output will be Displayed as
Step 5:
Onclicking submit button the value selected in drop-down is posted as an array.Let us assume we are using PHP to get this value.
[php]
if(!empty($_POST[‘check_list’])){ //Checking if check_list control is empty or not
foreach($_POST[‘check_list’] as $check){ //Looping through the array of values in foreach
print_r($check);//return the value of the variable
$test = implode(‘,’,$check);// implode tha array value to pass it in a query
}
}
[/php]
Your complete code will look like this
[html]
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery MultiSelect Dropdown</title>
<link rel="stylesheet" type="text/css" href="../jquery.multiselect.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../src/jquery.multiselect.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#check_list").multiselect();
});
</script>
</head>
<body id="test">
<form id="multiple" method="post" enctype="multipart/form-data">
<select title="Basic example" multiple="multiple" name="example-basic" size="5">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Mango</option>
<option value="4">Grapes</option>
<option value="5">Strawberry</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
if(isset($_POST[‘submit’])){
if(!empty($_POST[‘check_list’])){
foreach($_POST[‘check_list’] as $check){
print_r($check);
$test = implode(‘,’,$check);
}
}
$fruits = mysql_query("SELECT * FROM fruits WHERE fruit_id IN(".$test.")");
$fetch_fruits = mysql_fetch_array($fruits);
$name = $fetch_fruits[‘fruit_name’];
$desc = $fetch_fruits[‘desc’];
echo ‘<div>"’.$name.’"</div>’;
echo ‘<div>"’.$desc.’"</div>’;
}
?>
</body>
</html>
[/html]
For working example of Multi-select dropdown checkbox Click Here
Must know before reading this article
- PHP Basics
- HTML Basics
- Jquery





