Programming

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

Thursday, December 10th, 2015 PHP, Programming No Comments

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>

Tuesday, June 17th, 2014 Programming No Comments

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.

Name:
*
E-mail:
*
Website:

Comment:

Gender:
Female
Male
*


Your Input:

Name
Test@gmail.com
www.example.com
Test Comment
Female

Monday, May 26th, 2014 PHP, phpvalidation, Programmer, Programming No Comments

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]

Monday, May 19th, 2014 PHP, Programmer, Programming No Comments

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: &lt;webmaster@example.com&gt;’ . "\r\n";
$headers .= ‘Cc: mymd@example.com’ . "\r\n";
mail($to,$subject,$message,$headers);
?>
[/php]

Friday, April 25th, 2014 Programming No Comments

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.

Wednesday, April 23rd, 2014 PHP, Programmer, Programming No Comments

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:

Tuesday, April 15th, 2014 Programming No Comments

Validation Using Javascript

 [php]
<html>
<head>
<script type="text/javascript">
function vali()
{
if(document.myform.FirstName.value=="")
{
alert("Please enter the FirstName");
document.myform.FirstName.focus();
return false;
}
}
</script>
</head>
<form method="post" name="myform" onsubmit="return vali();">
Name : <input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</html>
[/php]

Output:
Name :

Wednesday, April 9th, 2014 javascript, PHP, Programming No Comments

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

drop_down

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
Monday, May 13th, 2013 Programming No Comments

Tutorial to get values from database on selection of dropdown in PHP

PHP Fetch Tutorial

Fetching Data From Database on selection of dropdown value

Step 1: 

Get the list of countries from database and populate in drop-down.

[php]
$ctry_qry = mysql_query(“SELECT * FROM countries ORDER BY name;”);?>
//Calling Function
<select name="”ctry”"> <option value="”&quot;">Select Country</option></select>
<select name="”ctry”"><option value="”<?PHP">”><!–?PHP echo $ctry[‘name’]; ?–></option></select>
[/php]

Consider that we choose  India from the dropdown list.

countries-dropdown-list-values-from-database

Step:2

          Add a simple javascript function which will run onchange

[javascript]
function reloaddata(ctryid) {
window.location.href="http://localhost/rotatetheglobe/admin/try.php?ctryid=" + ctryid;
}
[/javascript]

Step:3

        Reload the page in JS and pass the currently selected country id

values-fetched-from-db-on-country-selection

Step:4

Get the country id from query string and fetch the required values from the database

[php]
<?PHP</pre>
<div><code>if</code><code>(isset(</code><code>$_REQUEST</code><code>[</code><code>’ctryid'</code><code>])) {</code></div>
<div><code>$ctryinfo_qry</code> <code>= mysql_query(</code><code>"SELECT * FROM country_info where ctry_root_id=’"</code><code>.</code><code>$_REQUEST</code><code>[‘ctryid</code><code>’]."'</code> <code>ORDER BY ctry_info_id ;");</code></div>
<div><code>?></code></div>
<pre>[/php]

Fetch array is used to fetch the respective row from record set . Using fetch array in while loop is used get a new row of MySQL information until the condition is TRUE.When there are no more rows the function will return FALSE causing the while loop to stop!

[php]
<textarea id="msgpost" name="ctry_about" rows="10" cols="50"> <?php echo $ctry_inf[‘ctry_about’];?></textarea>
<!–?php } ?–>

[/php]

CLICK HERE to view the complete output

Possible Errors to occur:

  • JS Error
  • Couldn’t get the value from the query string
  • Page not found

Must Follow

  • Make Sure the querystring variable and the $_REQUEST variable is same
  • Make sure your onchange function is same name as that you call in your code.

Must know before reading this article

  • PHP Basics
  • HTML Basics
  • DB Handling

Coming Up:

  • How to configure a site to work in your local host when you are running windows
Monday, December 3rd, 2012 Programming No Comments
Request a Free SEO Quote