You are on page 1of 137

WORLD WIDE WEB ,

HTML AND PHP


K.VENKATESWARA RAO
ASST.PROFESSOR
DEPT. OF COMPUTER SCIENCE &
ENGINEERING

Typical Life cycle of a web


page

PHP INTRODUCTION
PHP stands for Personal Home Page, Hypertext
Preprocessor.
PHP is used to develop dynamic web
applications
PHP is server side scripting language
implemented by Rasmus Lerdorf in 1995 using
C and Perl technologies.

Features of PHP
Cross platform: It can run under any type of
operating system.
Cross server: It can run under different types
of web servers, like IIS, Apache , Tomcat etc.
Cross database: It supports any type of
database server.
PHP 5.0 MySQL: php 5.0 is providing MySQL
library to interact with MySQL Database.
PHP is a open source.

Features cont.
Php provides number of security functions to
apply security to applications(authentication).
Php supports few object oriented concepts
also.
Php supports different types of editors to
develop programs like notepad, edit+ etc.
Zend organization provides complete support
to php developers through online.
Php is easy to understand and easy to
develop.

Php is partially case sensitive language. In


functions point of view case insentive and
variables point of view case sensitive.
Every statement in php should end with
semicolon.
Php is loosely typed language thats why no
need to specify data types at the time of
declaration.
Variable names in php starts with $ symbol.
Php script we should include within the script
declation tag <?php . ?>

Web server: is a software used to run


the web applications. It handles
client request and sends response
back to the client.
Web browser: it is software used to
open web application from web
server.
Client side script: the script is
executed by the client system with
the help of web browser.
examples-HTML , JavaScript etc.
Server side script: the script is

Tools to work with PHP?

WAMP
LAMP
XAMPP
After installation of xampp we can find xampp
folder in destination location.it contains number of
subfolders
htdocs
tmp
php
apache
mysql

Steps to create and execute php


program
Open editor and implement php
script using declaration style tags.
Save this file in the root directory
with extension .php.
Open xampp control panel and start
apache server.
Open browser and send request to
the server to get the output of php
file.

Declaration style tags


Php
Php is
is providing
providing different
different types
types of
of declaration
declaration style
style tags.
tags.
1.Universal
1.Universal style
style tag:
tag:
<?php
<?php .
. ?>
?>

2.Php
2.Php Short
Short open
open tag:
tag:
<?
<? ..
.. ?>
?>

3.Asp
3.Asp style
style tag:
tag:
<%
<% .
. %>
%>

4.HTML
4.HTML style
style tag:
tag:

<script
<script language=php>
language=php>

</script>
</script>

Sample php program


First.php
<html>
<head>
<title>first PHPprogram</title>
</head>
<body>
<h1>hello world example</h1>
<?php
echo'HelloWorld';
print its such a perfect day;
?>
</body>
</html>

Types of variables in PHP


A variable is the name of the memory
location used to store values at the time of
execution.
Php is loosely typed language that why we
can create variables without data types.
In PHP, a variable starts with the $ sign,
followed by the name of the variable
$x = 10;
$y = 20.5;
$text = welcome to php

Local variables
Variable declaration within in the
function comes under local variable
declation.
We can access within the function
where we declared.
We can not access outside the
function.

<html>
<body>
<?php
function fun1()
{
$x = 200;
print $x;
}
function fun2()
{
$y = 100;
echo $y;
}
fun1();
fun2();
?>
</body>
</html>

Global Variable
Global variables we can access from
any function within the script.
By default we can not access global
variables from the function directly.
If you want to access global variables
use the keyword $GLOBALS

Example:
<?php
$sno=100;
function f1()
{
$sno=111;
echo $GLOBALS[sno];
echo $sno;
}
function f2()
{
global $sno;
$sno=200;
echo $sno;
}
fun1();
fun2();
?>

Data types in PHP


Data type describes categories of values that a
programming language can use.
A data type refers to the type of data that a
variable can hold.
PHP includes the following eight data types.
Integer
Floating point numbers
String
Boolean
Array
Object
Resource
Null

<?php
//boolean
$validUser = true;
//integer
$size = 15;
//floating point
$temp = 98.6;
//string
$cat = php programming;
//null
$here = null;
?>

Checking variable data


types
Php automatically determines a
variable data type from the content it
holds.
And if the variables content changes
over the duration of a script, the
language will automatically set the
variable to the appropriate new data
type.

Example which illustrates type


juggling
<?
//define string variable
$whoami = venkat;
//out put : string
echo gettype($whoami);
//assign new integer value to variable
$whoami = 99.8;
//output : double
echo gettype($whoami);
//destroy variable
unset($whoami);
//output: NULL
echo gettype($whoami);
?>

Array - represents a variable that stores


collection of related data elements. Each
individual element of an array can be
accessed by mentioning its index position.
Object - allows you to store data as well as
information for its processing. the data or
information stored within an object known
as properties and attributes.
Resource - refers to a special data type
that is used to store references to external
functions and resources of php.
NULL - refers to a special data type that
holds a single value, i.e., null.

Resource - refers to a special data type


that is used to store references to
external functions and resources of php .
Example:- database connection , FTP
connection etc.
<?php
$con=mysql_connect("localhost","root","");
echo $con;
Output:
resourcedatatype.ph
print "<br>";
p
echo get_resource_type($con);
Resource id #3
?>
mysql link

Types of operators
Operator is a decision maker in php
- simple as addition/subtraction
- complex as and/or conditional statement
Types of operators
- assignment operator (=)
i.e. $var=value;
- arithmatic operators (+,_,*,/,%)
i.e. $var1=1+2;
$var2=10-3;
$var3=12*4;
$var4=12/4;
- modulus is the remainder of a division operator
i.e. 10/3=3
10%3=1

- concatination operator ( . )
i.e. $var1=$var1. red;
OR $var1.=red;
- increment (++) and decrement ( -- )
operators.
i.e. $a++; $b--;
- placement of increment and decrement
operators are important.
- prefixing ( ++$a; ) will
increment/decrement and return the value.
- Postfixing ( $a++; ) will return the value,
and the increment/decrement.

example
<?php
$a=2;
print ++$a;
print "<br>";
print $a++."--".$a;
print "<br>";
$b=5;
print $b++;
?>

Comparison operators:
- assist in the decision making process of
conditional statements
- result in a boolean value
i.e. Yes or no, 1 or 0
- 6 main operators ( ==,!=,<,>,<=,>= )
examples:
( == ) - 1==1 is true, 1==2 is false
( != ) - 1!=1 is false, 1!=2 is true
( < ) - 1<1 is false, 1<2 is true
( <= ) - 1<=1 is true, 1<=2 is true
1<=0 is false
( > ) - 1>1 is false, 1>0 is true
( >= ) - 1>=1 is true, 1>=2 is false

Logical operators
Often used in conjunction with logical operators.
- logical operators ( &&,||,!,xor )
- ( and, && ) returns true if left and right sides
are not false.
- ( or, || ) returns true if left or right sides are
true.
- ( ! ) exclamation sign modifies a true, false
statement.
- ( xor ) returns true of either the left or right are
true.

example
$a=4;
$b=6;
$c=$a+$b;
$d=$a;
$a && $b !=5;
$a || $b ==$d;
$a + $b == $c;

Logi.php
<?php
$a=4;
$b=6;
$c=$a+$b;
$d=$a;
if($a&&$b!=5)
//if($a<5 && $b>5)
{
print "welcome";
echo "hello friends";
}
?>

Arrays
Array is a collection of
heterogeneous data types.
Php is loosely typed language thats
why we can store any type of values
in arrays.
Array contains number of elements ,
each element is a combination of
element
key and element value.
Syntax: variablename=array(ele1,ele2,ele3,
);
Ex:

$arr=array(10,20,30);

Example-1
<?php
$arr=array(10,20,30);
print_r($arr);
echo $arr[2];
print "<br>";
$arr1=array(40,'scott',70);
print_r($arr1);
print "<br>";
$arr2=array(0=>45,1=>'venkat',2=>67);
print_r($arr2);
?>

<?php
$arr=array();
$arr[0]=20;
$arr[1]=40;
$arr[2]='manager';
print_r($arr);
print "<br>";
//associative array
$arr1=array();
$arr1['lang']='php';
$arr1['manager']='scot';
$arr1['sex']='male';
print_r($arr1);
//counts number of elements
echo count($arr);
?>

<?php
$arr=array(10,5,20,30);
sort($arr);//ascending order with new keys
print_r($arr);
print "<br>";
rsort($arr);//descending order with new keys
print_r($arr);
print "<br>";
asort($arr);//ascending order with original keys
print_r($arr);
print "<br>";
echo array_sum($arr);//sum of array elements
print "<br>";
echo array_product($arr);//product of array elements
print "<br>";
echo array_push($arr,40);
print "<br>";
print_r($arr);
print "<br>";
echo array_pop($arr);
print "<br>";
echo array_shift($arr);
print "<br>";
echo array_unshift($arr,5);
?>

explode(),implode()
explode()-Splits up a string by a
specified delimiter and creates an
array of strings.
implode()- Creates a string by gluing
Example:
together
array elements
a specific
$stats_array = array('name',
'ssn', 'phone'); by
// implode()
creates
a string from
separator.
an array
$stats_string = implode(",", $array);
<?php
$colors="red green orange blue";// Create a string
echo $colors;
echo "<b>\$colors is a ". gettype($colors)."\n";
$colors=explode(" ",$colors);// Split up the string by spaces
print_r($colors);
?>

array_count_values() Returns an
array consisting of the values of an
array and the number of times each
value occurs in an array.
<?php
$colors=array("red", "blue", "green", "red", "yellow",
"red","blue");
$unique_count = array_count_values($colors);
print_r($unique_count)."<br />";
?>

Array_merge()-to merge the elements of 2 arrays.


Shuffle()- it shuffles the array elements.
<?php
$arr=array(10,20,30);
shuffle($arr);
print_r($arr);
print "<br>";
$arr1=array(50,60);
$arr2=array_merge($arr,$arr1);
print_r($arr2);
?>

Strings
PHP provides many functions with which you can format and
manipulate strings.
Formatting Strings with PHP
Specifier Description
d Display argument as a decimal number
b Display an integer as a binary number
c Display an integer as ASCII equivalent
f Display an integer as a floating-point number (double)
o Display an integer as an octal number
S Display argument as a string
x Display an integer as a lowercase hexadecimal number
X Display an integer as an uppercase hexadecimal number

Example:str1.php(htdocs)
<?php
$number = 543;
printf('Decimal: %d<br/>', $number);
printf('Binary: %b<br/>', $number);
printf('Double: %f<br/>', $number);
printf('Octal: %o<br/>', $number);
printf('String: %s<br/>', $number);
printf('Hex (lower): %x<br/>', $number);
printf('Hex (upper): %X<br/>', $number);
?>

strlen() function returns length of


the string.
<?php
$string=welcome;
Echo the length of string is :.strlen($string);
?>

Splitting the string into an array explode(seperator,


string);
Joining the array elements into a single string implode(seperator,array);
<?php
$string=kogent
Finding the position
of a string in another string
solutions;
strpos()
echo
the position of so in kogent solutions
is
:.strpos($string,
so);
int
strpos($strong,find,start);
?>

Repeating the same string many


times:
str_repeat() is used to repeat a
string for a specific number of times.
<?php
$string=kogent- ;
echo the repeated string is :.str_repeat($string,5);
?>

Reverseing a string strrev()


<?php
$string=kogent;
Echo the reversed string is :.strrev($string);
?>

Finding current date and


time
The date() function is used to format
the local time and date.

date(format, timestamp);
format- format in which the date
string to be displayed.
timestamp optional, it displays
current system date and time by
default.

Some of the characters that can be used with the


format parameter are as follows:
d specifies the day of the month(from 01 to 31)
D textual representation of the day in three letters
F full textual representation of a month(january)
t specifies number of days in the given month
g specifies 12 hour format of an hour (1 to 12)
l specifies full textual representation of a day
h - specifies 12 hour format of an hour (01 to 12)
i specifies minutes with leading zeros (00 to 59)
s specifies seconds with leading zeros (00 to 59)
Y four digit representation of a year
a specifies a lowercase am or pm
S specifies the english ordinal suffix for the day of
month(st,nd,rd, or th)
<?php
date_default_timezone_set('UTC');
echo date('l'). '<br>';
echo date('l dS \of F Y h: i: s a');
?>

Control structures
The if Statement
if (expression) {
// code to execute if the expression
evaluates to true
}
<?php
$mood = 'happy';
if ($mood == 'happy') {
echo "Hooray! Im in a good mood!";
}
?>

An if Statement That Uses


else
<?php
$mood = 'sad';
if ($mood == 'happy') {
echo "Hooray! Im in a good mood!";
}
else
{
echo "i am in $mood mood";
}
?>

The switch Statement


The switch statement is an alternative way of changing
flow, based on the evaluation of an expression.
switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}

example
<?php
$mood='happy';
switch($mood)
{
case 'happy':
echo 'Hooray! Im in a good mood!';
break;
case 'sad':
echo 'Awww. Dont be down!';
break;
default:
echo 'Im neither happy nor sad, but $mood.';
break;
}
?>

Using the ?: Operator


Syntax:
(expression) ? returned_if_expression_is_true :
returned_if_expression_is_false;
Example:
<?php
$mood = 'sad';
$text = ($mood == 'happy') ? "I am in a good
mood!" : "I am in a $mood mood.";
echo "$text";
?>

Loops
The while Statement
Syntax: while (expression) {
// do something
}
Example:
<?php
$counter = 1;
while ($counter <= 12) {
echo $counter.'times 2 is '.($counter * 2).'<br
/>';
$counter++;
}
?>

The do...while Statement


Syntax: do {
// code to be executed
} while (expression);
Example: <?php

$n=1;
do{
$n++;
echo $n;
echo "the number is" . $n . "<br>";
}while($n<5);
?>

The for Statement


Syntax:
for (initialization expression; test expression;
modification expression)
{// code to be executed}
Example:
<?php
for($counter=1; $counter<=12; $counter++)
{
echo $counter."times 4 is ".($counter*4)."<br>";
}
?>

The foreach loop


The foreach loop allows you to iterate over
elements in an array.
Syntax:version1
foreach(array as value)
{
Statement;
}
Version2:
foreach(array as key=>value)
{
Statement;
}

<?php
$arr=array("welcome to","hello friends","web
programming");
foreach($arr as $value)
{
echo "processing".$value."<br>";
}
?>
<?php
$arr=array("name"=>"venkateswara
rao","age"=>31,"address"=>"hyderabad");
foreach($arr as $key=>$value)
{
echo $key. " is " . $value."<br>";
}
?>

Handling file uploads


If user upload any file from browser to
server first that file will upload into
server tmp memory location.
We need to implement server side
script to move that file from tmp
location to some other location which
we had like it.
$_FILES an array of variables
related to file uploads.

$_FILES[userfile][tmp_name] is the place


where the file has been temporarily stored on
the web server.
$_FILES[userfile][name] - to get the
uploaded file name.
$_FILES[userfile][size] is the size of the file
in bytes.
$_FILES[userfile][type] is the MIME type of
the file for example, text/plain or image/gpeg.
$_FILES[userfile][error] - will give you error
codes associated with file upload.
Example
programs:c:/xampp/htdocs/fileupload1.html
/upload1.php

Connecting to database(MySql)
Php is providing php_mysql.dll library with
number of functionalities to connect with
mysql databse.
Mysql is open source RDBMS. It supports
number of objects like tables,views, etc.
The default username for mysql db is root
and it does not contain any password.
We can connect to mysql db through a
command prompt by executing mysql.exe file
c:/xampp/mysql/bin>mysql.exe
mysql>create database dbname;
mysql>use dbname;

phpmyadmin
It is a GUI used to connect with mysql db.
It is available with xampp download.
The url address to open phpmyadmin is
http://localhost/phpmyadmin.
insert we can insert records in a table
browse we can browse the table records
structure to change the structure of a table
sql we can execute our sql statements
export we can export database tables into
text files,pdf,excell,etc.
import we can import the exported file
empty we can delete the table records
drop we can delete the table structure

My sql interaction with php


php_mysql.dll provides more functions to connect with mysql
database.
mysql_connect:
By using this we can create a connection between php and mysql database.it
contains 3 arguments:

servername
Username
password

mysql_select_db:
to select database from mysql server,arguments are sql statement
and connection id.
mysql_query:
To execute sql query in mysql database. arguments are sql
statement and connection id.
mysql_error:
To get the error messages while executing mysql statements.
mysql_errno:
To get the error number while executing mysql statements.

To create connection between mysql


and php
<?php
if($con=mysql_connect(localhost, root, ))
{
echo connected. <br>;
echo $con; // resource type
}
else
echo mysql_error();
?>

Creating database
<?php
$con=mysql_connect("localhost","root");
if(mysql_query("create database venkat",$con))
echo "database created";
else
echo mysql_error();
?>

Creating table
<?php
$con=mysql_connect("localhost","root");
mysql_select_db(db_new,$con);
if(mysql_query("create table customer(sno int)",
$con))
echo table created";
else
echo mysql_error();
?>
Example:loginmysql.html
insert.php

Cookies and sessions


A cookie is often used to identify a
user.
A cookie is a small file that the
server embeds on the user's
computer.
Each time the same computer
requests a page with a browser, it
will send the cookie too.
With PHP, you can both create and
retrieve cookie values.

The Anatomy of a Cookie

Cookies are usually set in an HTTP


header
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

Setting Cookies with PHP

PHP providedsetcookie()function to set


a cookie.
This function requires upto six arguments
and should be called before <html> tag.
For each cookie
this
function
to be
setcookie(name,
value,
expire,
path,has
domain,
called separately.
security);

Exploring cookie attributes:


Name value- variable name and corresponding value to
be stored in
cookie
Expiration date - determines the time when to delete a

Path- identifies sites within various


paths in the same domain. Setting
this to the root (/)
allows entire domain to access
information stored in the cookie.
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


cookiesnameandagethese 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.
<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>

PHP - Sessions

A session creates a file in a temporary directory


on the server where registered session variables
and their values are stored.
This data will be available to all pages on the
site during that visit.

Starting a PHP Session


A PHP session is easily started by making a call
to the session_start()function.
It is recommended to put the call
tosession_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.

<?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>

To destroy the session


<?php
session_destroy();
?>
Differences between cookies and sessions
Cookies

sessions

Cookies will be stored in the


client system

Server system

Stores limited amount of data

Huge amount of data

Stores only text data

Stores any type of data

unsecured

secured

You might also like