Php
Php
<?php
…PHP code…
?>
SIMPLE PHP PROGRAM
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
WampServer
if (conditional test)
{
do this;
}
else
{
do this;
}
?>
Example
<?php
if ($temp >= 100)
{
echo 'Very hot!';
}
else
{
echo 'Within tolerable limits';
}
?>
Switch Statement
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
Example
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>
Looping Statements-while
<?php
// define number and limits for multiplication tables
$num = 11;
$upperLimit = 10;
$lowerLimit = 1;
There are three different kind of arrays and each array value is
accessed using an ID 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
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.
<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"; The foreach loop is used to loop through arrays
$numbers[4] = "five";
Functions:strlen,strrev,strtolower,strtoupper,strncmp,substr,
Web Concepts
Identifying Browser & Platform
PHP creates some useful environment variables that can be seen in the phpinfo.php
page that was used to setup the PHP environment.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies
the user's browser and operating system.
PHP provides a function getenv() to access the value of all the environment variables.
The information contained in the HTTP_USER_AGENT environment variable can be
used to create dynamic content appropriate to the borwser.
Example
<html>
<body>
<?php
$viewer = getenv( "HTTP_USER_AGENT" );
$browser = "An unidentified browser";
if( preg_match( "/MSIE/i", "$viewer" ) )
{
$browser = "Internet Explorer";
}
else if( preg_match( "/Netscape/i", "$viewer" ) )
{
$browser = "Netscape";
}
else if( preg_match( "/Mozilla/i", "$viewer" ) )
{
$browser = "Mozilla";
}
$platform = "An unidentified OS!";
if( preg_match( "/Windows/i", "$viewer" ) )
{
$platform = "Windows!";
}
else if ( preg_match( "/Linux/i", "$viewer" ) )
{
$platform = "Linux!";
}
echo("You are using $browser on $platform");
?>
</body>
</html>
Another example
<html>
<head>Test page</head>
<body>
The time is now
<?php
echo(date("l dS \of F Y h:i:s A") . "<br />");
?>
<hr>
</body>
</html>
Output:
Using HTML Forms
The most important thing to notice when dealing with HTML forms and PHP is
that any form element in an HTML page will automatically be available to
your PHP scripts.
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />"; The PHP default variable $_PHP_SELF is
echo "You are ". $_POST['age']. " years old."; used for the PHP script name and when
exit(); you click "submit" button then same PHP
}
script will be called
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Processing HTML Forms-
welcome.html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Welcome.php
<html>
<body>
</body>
</html>
Output
Get & Post Method
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding. In this scheme, name/value pairs are joined with equal signs and different
pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric
characters are replaced with a hexadecimal values. After the information is encoded it
is sent to the server.
Get Method
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ?
character.http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
Never use GET method if we have password or other sensitive information to be sent to the
server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment
variable.
The PHP provides $_GET associative array to access all the sent information using GET
method.
Example
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Post Method
The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP we can make sure that
your information is secure.
The PHP provides $_POST associative array to access all the sent information
using GET method.
Example
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
<?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>
Function 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 our 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>
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.
<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>
PHP Functions retruning
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.
<?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>
Cookies
Cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
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.
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);
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>
Session
.
Example 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
<?php
not
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>
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 we want to destroy a single session variable then we can use
unset() function to unset a session variable.
Here is the call which will destroy all the session variables
:<?php
session_destroy();
?>
Object Oriented
Programming in PHP
The general form for defining a new class in PHP is as follows:
<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
Insert data into MySQL
<?php
$dbhost = 'localhost:';
$dbuser = 'root';
$dbpass = ‘';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Getting Data From MySQL
Database
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Updating Data into MySQL
Database
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100">Employee Salary</td>
<td><input name="emp_salary" type="text" id="emp_salary"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
Deleting Data from MySQL
Database
<?php
if(isset($_POST['delete']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);