Professional Documents
Culture Documents
PHP Final Material
PHP Final Material
PHP Final Material
Unit-1 Introduction 18
► Conditional Statement
► Looping Statement
► Array- Types of Array(Numeric, Associative, Multi-dimensional)
► PHP Server variables
► Built-in-functions:
o String(print(),echo(),chr(),trim(),ltrim(),rtrim(),soundex(),str_word_count(),
strcmp(),stristr(),strstr(),strlen(), strpos(), strrev(), substr(), strtoupper(), strtolower(),
ucfirst(),ucword(),sucbstr_replace())
o Mathematical(abs(),sqrt(),log(),floor(),ceil(),pow(), max(),min())
o Date/Time(Date(),time(),getdate(),gettimeofday(), localtime(),checkdate())
Unit-3 Working with form , Cookie and Session 17
► Form elements- TextBox, TextArea, Password,RadioButton, Check Box, Combo Box, Image
► Buttons – Submit and Reset
► Uploading File to web server
► POST & GET method
► PHP include and require statement
► Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting Cookies.
► Basic of Session- Starting a Session, Destroying a session.
Unit-4 Database Connectivity and Error Handling 17
► PHP-MySQL architecture
► Database interaction –Creating and connecting database
► Executing commands- Selecting, Inserting, Updating, Deleting
► Small application development
► Error Handling- Try, Catch and Throw block, die() function
► Page redirection in PHP
Reference Book :
Web Page
A Web page is a document on the world wide web “With its own address”.
A web pages are delivered by web server to the user and displayed in web browser to act as a “retrieval
unit” for the information stored in within it.
A website consist of many web pages linked together under a common domain name.
A web page is a document written in HTML and can be viewed on any web browser.it is contained within
the web srever,which can be accessed by entering the URL(Uniform Resource Locator) for that web page,
and once it loaded,it appears on the user’s web browser.
A web page may contain text,links for other pages,graphics, videos etc.
The Web browser is connected to the Web server, where the website’s contents are hosted through
HTTP.
Website
► Website is a collection of related web pages that may contain text, images, audio and video. The first
page of a website is called home page. Each website has specific internet address (URL) that you need to
enter in your browser to access a website.
► A website is a collection of Web pages that share a single domain name. Websites can be created and
maintained by an individual, group, business or organization to serve a variety of purposes.
► Website is hosted on one or more servers and can be accessed by visiting its homepage using a
computer network. A website is managed by its owner that can be an individual, company or an
organization.
► The first website was created in 1990 by Tim Berners-Lee, a British physicist at CERN. 3 years later, in
1993, CERN announced that everyone could access and use the World Wide Web for free.
► Every page is a single HTML document, and all of them are connected through hyperlinks (or simply
“link”) which can be combined in a navigation bar for ease of use.
► Originally, websites were categorized by their top-level domains. Some examples include:
► Government agency websites = .gov
► Educational institutions’ websites = .edu
► Nonprofit organizations’ websites = .org
► Commercial websites = .com
► Information sites = .info
Static website
Static website is the basic type of website that is easy to create. You don't need the knowledge of web
programming and database design to create a static website. Its web pages are coded in HTML.
The codes are fixed for each page so the information contained in the page does not change and it looks
like a printed page.
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses
content from a database or Content Management System (CMS). Therefore, when you alter or update
the content of the database, the content of the website is also altered or updated.
Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.
Client side scripting generates content at the client computer on the basis of user input. The web
browser downloads the web page from the server and processes the code within the page to render
information to the user.
Fundamental of PHP
► PHP was originally created by Rasmus Lerdorf in 1995.
► It was used by him to maintain his personal web pages PHP code can embedded with HTML very easily no
need to call an external file to process data.
► PHP needs interpreter to process and convert its code into binary.
► PHP code is interpreted by a web server with a PHP processor module which generates the resulting web
page.
► Full form of PHP is hypertext preprocessor.
► It was previously known as personal home page
► PHP is one type of server side scripting language so PHP code executes on server rather than on client
► PHP is basically used to create dynamic web pages
► Dynamic web page's content vary according to place, time, user and behavior of user To generate such
type of website or webpage one neck-to use server side scripting language and many more tools &
technology like HTML JavaScript, CSS, AJAX, etc.
► PHP is one of the most popular and widely used accepted server side scripting language.
► PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.
► It handles dynamic content, database as well as session tracking for the website. o You can create sessions
in PHP.
► It can access cookies variable and also set cookies.
► It helps to encrypt the data and apply validation.
Features of PHP
► PHP is open source, free to download and use
► PHP is on different platforms (Windows, Linux, UNIX PHP is compatible with many servers, PHP supports
popular database servers (MySQL, Intermix, Grace Sybase, Solid PostgreSQL, Genere ODBC.ctc.)
► PHP has extremely useful text processing feature PHP is easy to learn.
► PHP combined with MySQL can develop in windows and serve on a unix platform)
► Online help and technical documentation is available.
► PHP a wide range of protocol
Advantages of PHP
► Some of PHP's main competitors are Perl, Microsoft Active Server Pages (ASP), Java Server Pages (JSP).
► In comparison to these products, PHP has many strengths including the followings
1 High performance
2 Interfaces to many different database systems
3 Built-in libraries for many common web tasks
4 Low cost
Operators
► An operator is any symbol used to perform an operation on a value. PHP operators can be classified into
the following three categories:
(1) Unary Operators
(2) Binary Operators
(3) Ternary operators
Unary Operators
i. Negation Operators
Operator Meaning Example Description Result
! Logical Negation $x=2, !($x==2) TRUE if the operand evaluates to TRUE
FALSE, FALSE if the operand evaluates
to TRUE
~ Bitwise Negation $x=2, $y=~$x One is added to the bits of $x and also $y=-3
reverse it's sign.
Variable Value
$_SERVER["SERVER ADMIN"] admin@127.0.0.1
$_SERVER["REMOTE_PORT] 1604
$_SERVER*"REQUEST_METHOD”+ GET
$_SERVER*“PHP_SELF"+ /index.php
$_SERVER["REQUEST_TIME"] 1366860955
Each of the parameters above can be empty, or have multiple expressions (separated by commas),
The example below defines a loop that starts with i=1. The loop will continue to run as long as is less
than, or equal to 5. I will increase by 1 each time the loop runs:
<?php
for ($i=1; $i<5; $i++)
echo "The number is “.$i."<br />";
?>
(2) while loop
The while loop executes a block of code while a condition is true.
Syntax
initializaion;
while (condition)
{ code to be executed;
increment/decrement;
}
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the loop runs:
<? php
$i=1;
while($i<=5)
{
echo "The number is ".$i."<br />";
$i++;
} ?>
3)do while loop
The do...while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true. Syntax
initialization;
do
{
code to be executed;
increment/decrement;
"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space
Example:
<?php
$str = "\n\n\n Hello World!\n\n\n";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>
Parameter Description
String Required. Specifies the string to check
Return Optional. Specifies the return value of the str_word_count() function.
Possible values:
0 - Default. Returns the number of words found
1 - Returns an array with the words from the string
2 - Returns an array where the key is the position of the word in the string, and value is
the actual word
Char Optional. Specifies special characters to be considered as words.
Parameter Description
String Required. Specifies the string to convert
Example:
<html>
<body>
<?php
echo ucfirst("hello world!");
?>
</body>
Parameter Description
Number Required. Specifies a number. If the number is of type float, the return type is also float,
otherwise it is integer
Example
<html>
<body>
<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
Parameter Description
Timestamp Optional. Specifies a Unix timestamp that defaults to the current local time, time(), if no
timestamp is specified
is_assoc Optional. Specifies whether to return an associative or indexed array. FALSE = the array
returned is an indexed array. TRUE = the array returned is an associative array. FALSE is
default.
5) checkdate
The checkdate() function is used to validate a Gregorian date.
Syntax: checkdate(month, day, year)
Parameter Description
Month Required. Specifies the month as a number between 1 and 12
Day Required. Specifies the day as a number between 1 and 31
Year Required. Specifies the year as a number between 1 and 32767
Example
<html>
<body>
<?php
var_dump(checkdate(12,31,2023));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
</body>
</html>
Introduction of HTML
In order to design a web page we need to write code to design it. This code is known as scripting language.
There are two types of scripting language. Server side Scripting Language and Client side Scripting Language.
HTML is basically client side Scripting language. In order to design static web sites (Sites that do not have
any database or does not store any client information are called static web sites) HTML is used. In order to
design dynamic web sites one has to use the server side scripting language that could be either ASP or PHP.
With server side scripting language we can store, retrieve, delete and edit the data.
Static Pages:
Static pages, as the name indicates, comprise static content (text or images). So you can only see the
contents of a web page without being able to have any interaction with it.
Dynamic Pages:
Dynamic pages are those where the content of the web page depend on user input. So interaction with
the user is required in order to display the web page. For example, consider a web page which requires a
number to be entered from the user in order to find out if it is even or odd. When the user enters the
number and clicks on the appropriate button, the number is sent to the web server, which in turn
returns the result to the user in an page.
HTML also provides some tags to create user interfaces like forms, textboxes, checkboxes, radio buttons,
pull down menu, password field, etc, to create different elements of user interface following tags are
used...
► Forms are a mechanism that allows users to enter different information through the controls given in the
forms and submit that information to server, Because of this they are used to create interactive web pages.
► The <FORM> tag comes at the beginning of any form. When you create a <FORM> tag, you also define the
script it uses and how it sends data using the ACTION and METHOD attributes:
Attribute Description
ACTION This attribute points the form to an URL that will accept the form's information and do
something with it. If you don't specify an ACTION, it sends the information back to the same
URL, the page came from.
METHOD This attribute tells the form how to send its information to the URL specified in ACTION. The
most common method is POST, which sends all the information from the form separately
from the URL. The other option for METHOD is GET, which attaches the information from
the form to the end of the URL.
GET POST
1. All the values passed to the target page will be 1. The values will be passed to the target page
displayed in the address bar without displaying into the address bar.
3. There is limitation in passing the number of 3. There isn't such limitation in passing the values.
values in this method.
For example:
…….
</FORM>
<INPUT>
The <INPUT> tag is used to indicate where user input is expected. This tag is used to create TEXTBOXES,
PASSWORD FIELDS, RADIO BUTTONS, CHECK BOXES and ACTION BUTTONS (SUBMIT, RESET) etc.
NAME This defines the name for the data. This field is required for all the types 0of input except
Submit and Clear.
SIZE This is the size of the input field in number of characters for text or password.
MAXLENGTH This specifies the maximum number of characters to be allowed for a text or password
field.
VALUE For a text or password field, it defines the default text displayed. For a check box or radio
button, it specifies the value that is returned to the server if the box or button is
selected. For the Submit and Reset buttons, it defines the text inside the button.
CHECKED This sets a check box or radio button to on. It has no meaning for any other type of
<INPUT> tag
TYPE This sets the type of input field you want to display.
The most common value of this attribute of the <INPUT> tag is TEXT. This attribute is used to create a
single line textbox. <INPUT TYPE=TEXT> creates a text box. Attributes are....
Attribute Description
Size This is the size of the input field in number of characters for text
MAXLENGTH This specifies the maximum number of characters to be allowed for a text.
Name This defines the unique name for the text box.
CODE OUTPUT
<HTML>
<HEAD> <TITLE> TEXT BOX</TITLE> </HEAD>
<BODY>
<FORM> Username:
USERNAME:
<INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME">
</FORM>
</BODY>
</HTML>
• With <TEXTAREA>, you can provide a field for someone to enter multiple lines of information. By
default, a <TEXTAREA> form shows a blank field four rows long and 40 characters wide. You can make it
any size you want by using the ROWS and COLS attributes in the tag. You can also specify some default
text by simply entering it between the <TEXTAREA> and </TEXTAREA> tags.
Attribute Description
WRAP It is used if you want to enable word wrap within a control, so that if a word doesn't have
enough space to fit itself it will be shifted into next line without breaking.
MAXLENGTH This specifies the maximum number of characters to be allowed for a text area.
Code Output
<HTML>
<HEAD><TITLE>TEXT
AREA</TITLE></HEAD>
<BODY><FORM>REMARKS: here, you can make any remarks.
<TEXTAREA ROWS=6 COLS=40 MAXLENGTH=500
NAME="REMARKS" WRAP>
HERE, YOU CAN MAKE ANY REMARKS.
REMARKS:
</TEXTAREA>
</FORM></BODY></HTML>
Very similar to the TYPE-TEXT is the TYPE-PASSWORD. It is exactly the same, except that for security it
displays" ***instead of the actual input.
SIZE This is the size of the input field in number of characters for password field.
MAXLENGTH This specifies the maximum number of characters to be allowed for a password field.
Name This defines the unique name for the password field.
Code OUTPUT
<HTML>
<HEAD><TITLE>PASSWORDFEILD
</TITLE></HEAD>
<BODY>
<FORM>
USERNAME <INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15 USERNAME:
NAME="USERNAME">
<BR><BR> PASSWORD:
PASSWORD: <INPUT TYPE-PASSWORD SIZE=10 MAXLENGTH=15
NAME="PASSWORD">
</FORM>
</BODY>
</HTML>
Creating Checkbox
CHECKBOX displays a simple check box that can be checked or left empty; use a check box when the
choice is yes or no and doesn't depend on anything else. Possible attributes to include with the TYPE,
include NAME (required). VALUE, and CHECKED (which defaults the check box as checked). Check boxes
are useful when you have a list of options, more than one, of which can be selected at a time CHECKBOX.
Attributes are.....
Attribute Description
NAME This defines the unique name for the Check box
VALUE This specifies the value to be passed to the target page if the checkbox is selected
<HTML><FORM><H2>HOBBIES</H2>
CRICKET<input TYPE-CHECKBOX VALUE=Cricket
CHECKED> Hobbies
MUSIC<INPUT TYPE=CHECKBOX VALUE=Music><BR>
Cricket Music
DANCING<INPUT TYPE=CHECKBOX VALUE=Dancing>
SINGING<INPUT TYPE=CHECKBOX Dancing Singing
VALUE=Singing><BR>
</FORM> </HTML>
RADIO BUTTON is a more complex version of a check box, allowing only one of a related set to be chosen.
You can group radio buttons together by using the NAME attribute; this keeps all buttons in the same
group under one NAME. Possible attributes to include with the TYPE, include NAME (required), VALUE,
and CHECKED.
Attribute Description
NAME This defines the unique name for the radio button
VALUE This specifies the value to be passed to the target page if radio button is selected
CHECKED This is used if we want default selection on any radio button, it is optional.
CODE OUTPUT
<HTML><FORM>
<head><title>radio button <title></head>
<body> GENDER
<form>
Gender <br><br> MALE FEMALE
<input type=radio name=”gender” value=”MALE”
checked> MALE
<input type=radio name=”gender” value=
“FEMALE”>FEMALE
</body>
</FORM> </HTML>
The <SELECT> element shows a list of choices in either a pop-up menu or a scrolling list. It's set up as an
opening and closing tag with a number of choices listed in between. Just like the <TEXTAREA> element,
the <SELECT> tag requires you to define a name. You can specify how many choices to show at once by
using the SIZE attribute. The attributes for the <SELECT> element are as follows:
Attribute Description
NAME This is required. It defines the name for the pull-down menu.
SIZE This attribute determines how many choices to show. If you omit SIZE or set it to 1, the
choices are shown as a drop-down list. If you set it to 2 or higher, it shows the choices in a
scroll box. If you set SIZE larger than the number of choices you have within <SELECT>, a
nothing choice is added. When the end user chooses this, it's returned as an empty field.
MULTIPLE This allows multiple selections. If you specify multiple, a scrolling window displays-
regardless of the number of choices or the setting of SIZE. To select more than one option,
it has to be clicked with CTRL key.
You present the choices the end user can make within the <SELECT> and </SELECT> tags. The choices
are listed inside the <OPTION> tag. The attributes for the <OPTION> tag are the following:
Attribute Description
Value This is the value to be assigned for the choice, which is what is sent back to the script, and
doesn't have to be the same as what is presented to the end user.
SELECTED If you want one of the choices to be a default, use the SELECTED option in the <OPTION>
tag.
CODE OUTPUT
<HTML> EDUCATION:
<HEAD> <TITLE>List Box </TITLE></HEAD>
B.C.A
<BODY> <FORM> EDUCATION:
EDUCATION:
<SELECT SIZE=4 NAME="EDUCATION”
B.C.A ^
MULTIPLE> B.B.A
V
<OPTION VALUE=BCA SELECTED>B.C.A.</OPTION>
B.A
<OPTION VALUE=BCA>B.C.A</OPTION>
<OPTION VALUE-BBA >B.B.A</OPTION>
<OPTION VALUE-BA >B.A.</OPTION>
SUBMIT displays a push button with the preset function of sending the data in the form to the server to be
processed by a server-side script. You can use the VALUE attribute with SUBMIT to provide text other than
Submit Query (the default) for the button.
CODE OUTPUT
<HTML>
<HEAD> <TITLE>SUBMIT.HTM</TITLE>
</HEAD>
<BODY> <FORM>
SUBMIT Query
<INPUT TYPE="SUBMIT"> <BR>
<INPUT TYPE="SUBMIT"
Send
VALUE="SEND">
</FORM><BODY>
</HTML>
Creating Reset Button
Display’s a push button with the preset function of clearing all the data in the form to its original value.
You can use the VALUE attribute with the RESET tag to provide text other than Reset (the default) for the
button.
CODE OUTPUT
<HTML>
<HEAD><TITLE>RESET.HTM</TITLE> Username ABC
</HEAD> Password
<BODY> <FORM>
Reset
USERNAME:
<INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME" VALUE=ABC> <BR> Clear
PASSWORD:
<INPUT TYPE=PASSWORD SIZE=10
MAXLENGTH=15 NAME="PASSWORD">
<BR><INPUT TYPE="RESET">
<BR>
<INPUT TYPE="RESET" VALUE="CLEAR">
</FORM><BODY></HTML>
The following code demonstrates the use of GET method, ACTION and SUBMITS buttons.
CODE OUTPUT
<HTML>
<HEAD> <TITLE>FORMDEMO.HTM Username ABC
</TITLE></HEAD> Password
<BODY>
Send
<FORM ACTION="BLANK.HTML" METHOD="GET">
USERNAME: <INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME" VALUE=ABC > <BR> Clear
PASSWORD:
<INPUT TYPE=PASSWORD SIZE=10 MAXLENGTH=15
NAME="PASSWORD">
<BR>
ACTION calls the BLANK HTML File when
<INPUT TYPE="SUBMIT" VALUE="SEND"> <BR>
you click on Submit Button.
<INPUT TYPE="RESET" VALUE="CLEAR">
</FORM>
<BODY>
</HTML>
<HTML>
<BODY>
File called by ACTION.
</BODY>
</HTML>
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the
user is allowed to upload.
In the following example we add some restrictions to the file upload. The user may only upload gif or
jpeg files and the file size must be under 20 kb and the temporary copy of the uploaded files will be
placed in the PHP temp folder on the server.
These temporary copied files will disappeared when the script ends. To store the uploaded file we need
to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size") < 20000))
{
if ($_FILES["file"]["error") > 0)
echo "Return Code: ".$_FILES["file"]["error"]."<br />";
else
(
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type:".$_FILES["file"]["type"]."<br />";
echo "Size:". ($_FILES["file"]["size"]/1024). " Kb<br />";
echo "Temp file: ".$_FILES["file"]["tmp_name"]."<br/>";
if (file_exists("upload/".<$_FILES["file"]["name"]))
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use
the include statement. Otherwise, in case of Framework or a complex PHP application coding,always use
the require statement to include a key file to the flow of execution. This will help avoid compromising
your application's security and integrity, just in-case one key file is accidentally missing.
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling file:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php
include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
PHP include vs. require
The require statement is also used to include a file into the PHP code.
PHP Cookies
► PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
user.
► Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.
► In short, cookie can be created, sent and received at server end.
► Note: PHP Cookie must be used before <html> tag.
Create Cookies With PHP
► A cookie is created with the setcookie() function.
► Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
► Only the name parameter is required. All other parameters are optional.
► PHP Create/Retrieve a Cookie
► The following example creates a cookie named "user" with the value "John Doe". The cookie will expire
after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select
the directory you prefer).
PHP Session
► PHP session is used to store and pass information from one page to another temporarily (until user close
the website).
► PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
► PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.
► When you work with an application, you open it, do some changes, and then you close it. This is much
like a Session. The computer knows who you are. It knows when you start the application and when you
end. But on the internet there is one problem: the web server does not know who you are or what you
do, because the HTTP address doesn't maintain state.
► Session variables solve this problem by storing user information to be used across multiple pages (e.g.
username, favorite color, etc). By default, session variables last until the user closes the browser.
► So; Session variables hold information about one single user, and are available to all pages in one
application.
► Tip: If you need a permanent storage, you may want to store the data in a database.
<?php
// Start the session
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
► Another way to show all the session variable values for a user session is to run the following code:
► Example
<?php
session_start();
?>
<html>
<body>
<?php
Web Server
Web page
MySQL PHP
Database