Galaxeepro.com

Welcome to Online Tutorial, here you can learn about Web Designing, PHP, and Asp.net, and Hacking Trick´s.

How PHP Works

The php.ini File

PHP.ini is very useful and it is a configuration file that is used to customize behavior of PHP at runtime.The Settings in which  upload directory, register global variables, display errors, log errors, max uploading size setting, maximum time to execute a script and other configurations is written in this file.

Basic PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.


Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Comments in PHP

1. # or // :- Start with # or // is a comment sign, which is not read by Browser.

<h1>This is an <?php # echo 'simple';?> example</h1>

<h1>This is an <?php // echo 'simple';?> example</h1>

2. /*...*/ :- It is a second example for comment multiple line.
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you −

Creating a PHP Function
Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Please refer to PHP Function Reference for a complete set of useful functions.
Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −

<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}

/* Calling a PHP Function */
writeMessage();
?>

</body>
</html>

This will display following result −

You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.

<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>

This will display following result −

Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.

Following example depicts both the cases.

<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num)
{
$num += 5;
}

function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

This will display following result −

Original Value is 10
Original Value is 16

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.

<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";
?>

</body>
</html>

This will display following result −

Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function's caller doesn't pass it.

Following function prints NULL in case use does not pass any value to this function.

<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>

</body>
</html>

This will produce following result −

This is test

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.

<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>

</body>
</html>

This will display following result −

Hello

PHP Buit in Function

PHP is very rich in terms of Buil-in functions. Here is the list of various important function categories. There are various other function categories which are not covered here.

Select a category to see a list of all the functions related to that category.

Superglobals

Superglobals — Superglobals are built-in variables that are always available in all scopes

Description

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

PHP 5 Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-data.


PHP - A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:

Example

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome John
Your email address is john.doe@example.com

The same result could also be achieved using the HTTP GET method:

Example

<html>
<body>

<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.

Note Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send and retrieve form data.

However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!


GET vs. POST

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.


When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!


When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

Note Developers prefer POST for sending form data.

PHP - Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.

  • for − loops through a block of code a specified number of times.

  • while − loops through a block of code if and as long as a specified condition is true.

  • do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.

  • foreach − loops through a block of code for each element in an array.

We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

for loop in Php

Syntax

for (initialization; condition; increment)  {     code to be executed;  }  

The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −

<html>
<body>

<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}

echo ("At the end of the loop a=$a and b=$b" );
?>

</body>
</html>

This will produce the following result −

At the end of the loop a=50 and b=25  

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

for loop in PHP

Syntax

while (condition)  {     code to be executed;  }  

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.

<html>
<body>

<?php
$i = 0;
$num = 50;

while( $i < 10)
{
$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );
?>

</body>
</html>

This will produce the following result −

Loop stopped at i = 10 and num = 40   

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do  {     code to be executed;  }  while (condition);  

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10 −

<html>
<body>

<?php
$i = 0;
$num = 0;

do{
$i++;
}

while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>

</body>
</html>

This will produce the following result −

Loop stopped at i = 10  

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)  {     code to be executed;    }  

Example

Try out following example to list out the values of an array.

<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −

Value is 1  Value is 2  Value is 3  Value is 4  Value is 5  

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

PHP Break Statement

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.

<html>
<body>

<?php
$i = 0;

while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>

</body>
</html>

This will produce the following result −

Loop stopped at i = 3  

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

PHP Continue Statement

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.

<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −

Value is 1  Value is 2  Value is 4  Value is 5  

PHP - Decision Making

The if, elseif ...else and switch statements are used to take decision based on the different condition.

You can use conditional statements in your code to make your decisions. PHP supports following three decision making statements −

Decision making statements in PHP
  • if...else statement − use this statement if you want to execute a set of code when a condition is true and another if the condition is not true

  • elseif statement − is used with the if...else statement to execute a set of code if one of the several condition is true

  • switch statement − is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.

The If...Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

Syntax

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, Otherwise, it will output "Have a nice day!":

<html>
<body>

<?php
$d=date("D");

if ($d=="Fri")
echo "Have a nice weekend!";

else
echo "Have a nice day!";
?>

</body>
</html>

It will produce the following result −

The ElseIf Statement

If you want to execute some code if one of the several conditions are true use the elseif statement

Syntax

if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice day!" −

<html>
<body>

<?php
$d=date("D");

if ($d=="Fri")
echo "Have a nice weekend!";

elseif ($d=="Sun")
echo "Have a nice Sunday!";

else
echo "Have a nice day!";
?>

</body>
</html>

It will produce the following result −

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression)
{
case label1:
code to be executed if expression = label1;
break;

case label2:
code to be executed if expression = label2;
break;
default:

code to be executed
if expression is different
from both label1 and label2;
}

Example

The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lable matches then statement will execute any specified default code.

<html>
<body>

<?php
$d=date("D");

switch ($d)
{
case "Mon":
echo "Today is Monday";
break;

case "Tue":
echo "Today is Tuesday";
break;

case "Wed":
echo "Today is Wednesday";
break;

case "Thu":
echo "Today is Thursday";
break;

case "Fri":
echo "Today is Friday";
break;

case "Sat":
echo "Today is Saturday";
break;

case "Sun":
echo "Today is Sunday";
break;

default:
echo "Wonder which day is this ?";
}

?>
</body>
</html>

It will produce the following result −

Today is Saturday

PHP - Arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.

  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.

  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )
{
echo "Value is $value <br />";
}

/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>

This will produce the following result −

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>
<body>

<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>

This will produce the following result −

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39


PHP - File Inclusion

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

  • The include() Function
  • The require() Function

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

<a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

<html>
<body>

<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>

</body>
</html>

It will produce the following result −

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

<html>
<body>

<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>

</body>
</html>

This will produce the following result −

This is an example to show how to include wrong PHP file!  

Now lets try same example with require() function.

<html>
<body>

<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>

</body>
</html>

This time file execution halts and nothing is displayed.

NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

PHP - Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users −

  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

  • Browser stores this information on local machine for future use.

  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

This chapter will teach you how to set cookies, how to access them and how to delete them.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser's headers might look something like this −

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);  

Here is the detail of all the arguments −

  • Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

  • Value − This sets the value of the named variable and is the content that you actually want to store.

  • Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

  • Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

  • Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

  • Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age these cookies will be expired after one hour.

<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>

<head>
<title>Setting Cookies with PHP</title>
</head>

<body>
<?php echo "Set Cookies"?>
</body>

</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html>

<head>
<title>Accessing Cookies with PHP</title>
</head>

<body>

<?php
echo $_COOKIE["name"]. "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>

</body>
</html>

You can use isset() function to check if a cookie is set or not.

<html>

<head>
<title>Accessing Cookies with PHP</title>
</head>

<body>

<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";

else
echo "Sorry... Not recognized" . "<br />";
?>

</body>
</html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired −

<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>

<head>
<title>Deleting Cookies with PHP</title>
</head>

<body>
<?php echo "Deleted Cookies" ?>
</body>

</html>

 

PHP - Sessions

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.

The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result −

<?php
session_start();

if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>

<head>
<title>Setting up a PHP session</title>
</head>

<body>
<?php echo ( $msg ); ?>
</body>

</html>

It will produce the following result −

You have visited this page 2in this session.

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −

<?php     unset($_SESSION['counter']);  ?>  

Here is the call which will destroy all the session variables −

<?php     session_destroy();  ?>  

Turning on Auto Session

You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

<?php
session_start();

if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}
else {
$_SESSION['counter']++;
}

$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";

echo ( $msg );
?>
<p>
To continue click following link <br />

<a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>

It will produce the following result −

You have visited this page 1in this session.

To continue click following link

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

 

PHP - File Uploading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps −

  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.

  • The user clicks the browse button and selects a file to upload from the local PC.

  • The full path to the selected file appears in the text filed then the user clicks the submit button.

  • The selected file is sent to the temporary directory on the server.

  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.

  • The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.

An uploaded file could be a text file or image file or any document.

Creating an upload form

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

$expensions= array("jpeg","jpg","png");

if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}

if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}

if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else{
print_r($errors);
}
}
?>
<html>
<body>

<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>

</body>
</html>

It will produce the following result −

Creating an upload script

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables −

  • $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.

  • $_FILES['file']['name'] − the actual name of the uploaded file.

  • $_FILES['file']['size'] − the size in bytes of the uploaded file.

  • $_FILES['file']['type'] − the MIME type of the uploaded file.

  • $_FILES['file']['error'] − the error code associated with this file upload.

Example

Below example should allow upload images and gives back result as uploaded file information.

<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

$expensions= array("jpeg","jpg","png");

if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}

if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}

if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else{
print_r($errors);
}
}
?>
<html>
<body>

<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>

<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>

</form>

</body>
</html>

It will produce the following result −

PHP - Sending Emails using PHP

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this −

mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@tutorialspoint.com

Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this −

[mail function]
; For Win32 only.
SMTP =

; For win32 only
sendmail_from =

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

 

Now you are ready to go −

Sending plain text email

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.

mail( to, subject, message, headers, parameters );  

Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the send mail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Sending HTML email

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.

<html>

<head>
<title>Sending HTML email using PHP</title>
</head>

<body>

<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";

$header = "From:abc@somedomain.com \r\n";
$header = "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";

$retval = mail ($to,$subject,$message,$header);

if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>

</body>
</html>

Sending attachments with email

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.

<?php
// request variables // important
$from=$_REQUEST["from"];
$emaila=$_REQUEST["emaila"];
$filea=$_REQUEST["filea"];

if ($filea)
{
function mail_attachment ($from , $to, $subject, $message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type

$start = strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment

$email_from = $from; // Who the email is from
$subject = "New Attachment Message";

$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to

$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$msg_txt="\n\n You have recieved a new attachment message from $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_txt . "\n\n";
$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);

if($ok)
{
echo "File Sent Successfully.";
unlink($attachment); // delete a file after attachment sent.
}

else
{
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "youremailaddress@gmail.com", "subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?>

<html>
<head>

<script language="javascript" type="text/javascript">
function CheckData45()
{
with(document.filepost)
{
if(filea.value != "")
{
document.getElementById('one').innerText = "Attaching File ... Please Wait";
}
}
}
</script>

</head>
<body>

<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<form name="filepost" method="post" action="file.php" enctype="multipart/form-data" id="file">

<table width="300" border="0" cellspacing="0" cellpadding="0">
<tr valign="bottom">
<td height="20">Your Name:</td>
</tr>

<tr>
<td><input name="from" type="text" id="from" size="30"></td>
</tr>

<tr valign="bottom">
<td height="20">Your Email Address:</td>
</tr>

<tr>
<td class="frmtxt2"><input name="emaila" type="text" id="emaila" size="30"> </td>
</tr>

<tr>
<td height="20" valign="bottom">Attach File:</td>
</tr>

<tr valign="bottom">
<td valign="bottom"><input name="filea" type="file" id="filea" size="16"></td>
</tr>

<tr>
<td height="40" valign="middle"><input name="Reset2" type="reset" id="Reset2" value="Reset">
<input name="Submit2" type="submit" value="Submit" onClick="return CheckData45()"></td>
</tr>
</table>

</form>

<center>
<table width="400">
<tr>
<td id="one">
</td>
</tr>
</table>
</center>

</td>
</tr>
</table>

</body>
</html>

MySQL Example

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

  

<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

dbconfig.php

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username'); // DB username
define('DB_PASSWORD', 'password'); // DB password
define('DB_DATABASE', 'database'); // DB name
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die( "Unable to connect");
$database = mysql_select_db(DB_DATABASE) or die( "Unable to select database");
?>

Logout.php

<?php
session_start();
session_unset();
$_SESSION['FBID'] = NULL;
$_SESSION['FULLNAME'] = NULL;
$_SESSION['EMAIL'] = NULL;
header("Location: index.php"); // you can enter home page here ( Eg : header("Location: " ."http://www.krizna.com");
?>

Functions.php

<?php
require 'dbconfig.php';
function checkuser($fuid,$ffname,$femail){
$check = mysql_query("select * from Users where Fuid='$fuid'");
$check = mysql_num_rows($check);
if (empty($check)) { // if new user . Insert a new record
$query = "INSERT INTO Users (Fuid,Ffname,Femail) VALUES ('$fuid','$ffname','$femail')";
mysql_query($query);
} else { // If Returned user . update the user record
$query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'";
mysql_query($query);
}
}?>

Database

CREATE TABLE IF NOT EXISTS `Users` (
`UID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Fuid` varchar(100) NOT NULL,
`Ffname` varchar(60) NOT NULL,
`Femail` varchar(60) DEFAULT NULL,
PRIMARY KEY (`UID`)
);

PHP - Facebook Login

We can use Facebook login to allow the users to get access into the websites. This page will explain you about login with facebook PHP SDK.

Login With Facebook

  • Need to go https://developers.facebook.com/apps/ and click on add a new group button to make the app ID.

  • Choose Website

  • Give an app name and click on Create New Facebook App ID

  • Click on Create app ID

  • Click on Skip Quick Test

On Final stage, it will show as below shown image.

facebook

fbconfig.php file overview

  • Now download zip from here
  • Now open fbconfig.php file and add you app ID and app Secrete

FacebookSession::setDefaultApplication( 'your app ID','App Secrete ' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('You web address' );

 

Finally fbconfig.php file as shown below −

<?php

session_start();

// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;

// init app with app id and secret
FacebookSession::setDefaultApplication( '496544657159182','e6d239655aeb3e496e52fabeaf1b1f93' );

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://www.tutorialspoint.com/' );

try {
$session = $helper->getSessionFromRedirect();
}

catch( FacebookRequestException $ex ) {
// When Facebook returns an error
}

catch( Exception $ex ) {
// When validation fails or other local issues
}

// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();

// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID

/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;

/* ---- header location after session ----*/
header("Location: index.php");
}
else
{
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>

Login page Overview

Login page is used to login into FB

<?php
session_start();
session_unset();

$_SESSION['FBID'] = NULL;
$_SESSION['FULLNAME'] = NULL;
$_SESSION['EMAIL'] = NULL;
header("Location: index.php");
?>

Index.php

Index page is as shown below.

<?php
session_start();
?>
<html xmlns:fb="http://www.facebook.com/2008/fbml">

<head>
<title>Login with Facebook</title>
<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
</head>

<body>
<?php if ($_SESSION['FBID']): ?> <!-- After user login -->

<div class="container">

<div class="hero-unit">
<h1>Hello <?php echo $_SESSION['USERNAME']; ?></h1>
<p>Welcome to "facebook login" tutorial</p>
</div>

<div class="span4">

<ul class="nav nav-list">
<li class="nav-header">Image</li>

<li><img src="https://graph.facebook.com/<?php echo $_SESSION['FBID']; ?>/picture"></li>

<li class="nav-header">Facebook ID</li>
<li><?php echo $_SESSION['FBID']; ?></li>

<li class="nav-header">Facebook fullname</li>

<li><?php echo $_SESSION['FULLNAME']; ?></li>

<li class="nav-header">Facebook Email</li>

<li><?php echo $_SESSION['EMAIL']; ?></li>

<div><a href="logout.php">Logout</a></div>

</ul>

</div>
</div>

<?php else: ?> <!-- Before login -->

<div class="container">
<h1>Login with Facebook</h1>
Not Connected

<div>
<a href="fbconfig.php">Login with Facebook</a>
</div>

<div>
<a href="http://www.tutorialspoint.com" title="Login with facebook">More information about Tutorialspoint</a>
</div>
</div>

<?php endif ?>

</body>
</html>

It will produce the result here. Before trying this example, please logout your face book account in your browser.

Logout Facebook

Below code is used to logout facebook.

<?php 
session_start();.
session_unset();

$_SESSION['FBID'] = NULL;
$_SESSION['FULLNAME'] = NULL;
$_SESSION['EMAIL'] = NULL;
header("Location: index.php");
?>

jQuery AJAX Method

The parameters specifies one or more name/value pairs for the AJAX request.

Possible names/values in the table below:

Name Value/Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions)
contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context Specifies the "this" value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object

1. ajaxSetup()

$("button").click(function(){
    $.ajaxSetup({url: "demo_ajax_load.txt", success: function(result){
        $("div").html(result);}});
    $.ajax();
});

2. get() Method

Example

Send an HTTP GET request to a page and get a result back:

 $("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

Definition and Usage

The $.get() method loads data from the server using a HTTP GET request.
Examples

Request "test.php", but ignore return results:
$.get("test.php");
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
Request "test.php" and pass arrays of data to the server (ignore return results):
$.get("test.php", { 'colors[]' : ["Red","Green","Blue"] });
Request "test.php" and alert the result of the request:
$.get("test.php", function(data){
alert("Data: " + data);
});
Syntax
$.get(URL,data,function(data,status,xhr),dataType)
Parameter Description
URL Required. Specifies the URL you wish to request
data Optional. Specifies data to send to the server along with the request
function(data,status,xhr) Optional. Specifies a function to run if the request succeeds
Additional parameters:
  • data - contains the resulting data from the request
  • status - contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")
  • xhr - contains the XMLHttpRequest object
dataType Optional. Specifies the data type expected of the server response.
By default jQuery performs an automatic guess.
Possible types:
  • "xml" - An XML document
  • "html" - HTML as plain text
  • "text" - A plain text string
  • "script" - Runs the response as JavaScript, and returns it as plain text
  • "json" - Runs the response as JSON, and returns a JavaScript object
  • "jsonp" - Loads in a JSON block using JSONP. Will add an "?callback=?" to the URL to specify the callback

3. jQuery getJSON() Method

Example

Get JSON data using an AJAX request, and output the result:

 $("button").click(function(){
    $.getJSON("demo_ajax_json.js", function(result){
        $.each(result, function(i, field){
            $("div").append(field + " ");
        });
    });
});

Definition and Usage

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.


Syntax

$(selector).getJSON(url,data,success(data,status,xhr))

Parameter Description
url Required. Specifies the url to send the request to
data Optional. Specifies data to be sent to the server
success(data,status,xhr) Optional. Specifies the function to run if the request succeeds
Additional parameters:
  • data - contains the data returned from the server.
  • status - contains a string containing request status ("success", "notmodified", "error", "timeout", or "parsererror").
  • xhr - contains the XMLHttpRequest object

4. jQuery ajaxComplete() Method

Example

Show a "loading" indicator image while an AJAX request is going on:

$(document).ajaxStart(function(){
    $("#wait").css("display", "block");
});

$(document).ajaxComplete(function(){
    $("#wait").css("display", "none");
});

Definition and Usage

The ajaxComplete() method specifies a function to be run when an AJAX request completes.

Note: As of jQuery version 1.8, this method should only be attached to document.

Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.


Syntax

$(document).ajaxComplete(function(event,xhr,options))

Parameter Description
function(event,xhr,options) Required. Specifies the function to run when the request completes
Additional parameters:
  • event - contains the event object
  • xhr - contains the XMLHttpRequest object
  • options - contains the options used in the AJAX request

Example

  

<button>Change Content</button>

<div id="wait" style="display:none;width:69px;height:89px;border:1px solid black;position:absolute;top:50%;left:50%;padding:2px;"> <img src='demo_wait.gif' width="64" height="64" /><br>Loading..</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
$("button").click(function(){
$("#txt").load("demo_ajax_load.asp");
});
});
</script>

Output

Let AJAX change this text

PHP Sending E-mails

By using PHP scripts, emails can be sent directly.

PHP mail() Function

PHP mail() function is used to send emails.

Syntax:

mail(to,subject,message,headers,parameters) 

This mail() function accepts 5 parameters as follows and
(the last 2 are optional).

Parameters Details
to The recipient’s email address.
subject The email’s subject line.
message The actual email body where you can insert main messages..
headers Additional parameters such as “From”, “Cc”, “Bcc” etc.
parameters Optional parameters.

PHP Simple E-Mail

Example:

  

<?php
if(isset($_POST["SubmitBtn"])){

$to = "someone@example.com";
$subject = "Contact mail";
$from=$_POST["email"];
$msg=$_POST["msg"];
$headers = "From: $from";

mail($to,$subject,$msg,$headers);
echo "Email successfully sent.";
}
?>

<form id="emailForm" name="emailForm" method="post" action="" >
<table width="100%" border="0" align="center" cellpadding="4" cellspacing="1">
<tr>
<td colspan="2"><strong>Online Contact Form</strong></td>
</tr>
<tr>
<td>E-mail :</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td>Message :</td>
<td>
<textarea name="msg" cols="45" rows="5" id="msg"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="SubmitBtn" type="submit" id="SubmitBtn" value="Submit"></td>
</tr>
</table>
</form>

PHP E-Mail Form

Example:

  

<?php
if(isset($_POST["SubmitBtn"])){

$to = "someone@example.com";
$subject = "Contact mail";
$from=$_POST["email"];
$msg=$_POST["msg"];
$headers = "From: $from";

mail($to,$subject,$msg,$headers);
echo "Email successfully sent.";
}
?>

<form id="emailForm" name="emailForm" method="post" action="" >
<table width="100%" border="0" align="center" cellpadding="4" cellspacing="1">
<tr>
<td colspan="2"><strong>Online Contact Form</strong></td>
</tr>
<tr>
<td>E-mail :</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td>Message :</td>
<td>
<textarea name="msg" cols="45" rows="5" id="msg"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="SubmitBtn" type="submit" id="SubmitBtn" value="Submit"></td>
</tr>
</table>
</form>

Sending HTML E-Mail

When you send a text message using PHP, then email content will be treated as ordinary text. HTML tags also.

You have to specify a Mime version, content type and character set to send an HTML email.

Example:

  

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a <strong>HTML</strong> test email message.";
$from = "me@example.com";
$headers = "From:" . $from\r\n;
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";

mail($to,$subject,$message,$headers)
?