0% found this document useful (0 votes)
8 views

Unit V PHP

Uploaded by

Samarth Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit V PHP

Uploaded by

Samarth Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

SINHGAD INSTITUTE OF MANAGEMENT, PUNE

SINHGAD INSTITUTE OF TECHNOLOGY, LONAVALA


MASTER OF COMPUTER
DEPARTMENT APPLICATION
OF ELECTRONICS & TELECOMMUNICATION

UNIT V
PHP

✓ Working with Arrays


✓ Installing and Configuring
✓ Decision Making, Flow Control and Loops
✓PHP
✓ Introduction to Laravel
✓ Introduction to PHP and
the Web Server Architecture, ✓ Creating a Dynamic HTML Form with PHP
PHP Capabilities ✓ Database Connectivity with MySQL
✓ PHP and HTTP Environment ✓ Performing basic database operations
Variables. (CRUD)
✓ Using
GET, POST, REQUEST, SESSION, and
✓ Variables , Constants, Data
COOKIE Variables
Types , Operators
MASTER OF COMPUTER APPLICATION
1
Unit Objective

I. To learn the fundamentals of PHP


II. To learn the different web technologies like CGI,PHP.
III. To understand the basic concept of Dynamic script in php.
IV. To learn the concept of database connectivity in PHP.

Unit Outcomes

i. To study the principles of PHP


ii. To understand & implement the PHP programming.
iii. To understand and learn the basic fundamental of PHP.

MASTER OF COMPUTER APPLICATION


2
Introduction to PHP?
▪ What is HTML?
❑ PHP is an acronym for "PHP: Hypertext Preprocessor“.
❑ PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
❑ PHP is a widely-used, free, and efficient alternative to
Microsoft's ASP.
❑ PHP is a Loosely Typed Language
❑ It is the biggest blogging system on the web (WordPress).
❑ PHP files can contain text, HTML, CSS, JavaScript, and PHP
code.
❑ PHP code are executed on the server, and the result is returned
to the browser as plain HTML
❑ PHP files have extension ".php"

MASTER OF COMPUTER APPLICATION


3
Introduction to PHP?
❑ What are features of PHP ?
✓ PHP can generate dynamic page content
✓ PHP can create, open, read, write, delete, and close files on the
server
✓ PHP can collect form data
✓ PHP can send and receive cookies
✓ PHP can add, delete, modify data in your database
✓ PHP can be used to control user-access
✓ PHP can encrypt data

MASTER OF COMPUTER APPLICATION


4
Basic of PHP?
➢ Creating PHPVariables
 In PHP, a variable starts with the $ sign, followed by the name of
the variable.
 A variable can have a short name or a more descriptive name .
➢ Rules for PHP variables:
✓ A variable starts with the $ sign, followed by the name of the
variable.
✓ A variable name must start with a letter or the underscore character.
✓ A variable name cannot start with a number
✓ A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
✓ Variable names are case-sensitive ($age and $AGE are two different
variables)
MASTER OF COMPUTER APPLICATION
5
Basic of PHP?
 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
?>
 <html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
 </html>

MASTER OF COMPUTER APPLICATION


6
Basic of PHP?
 Comments in PHP
➢ A comment in PHP code is a line that is not read/executed as part of the
program.
➢ Its only purpose is to be read by someone who is looking at the code.
➢ Comments can be used to:
➢ Let others understand what you are doing
➢ Comments can remind you of what you were thinking when you wrote the code

 1) Single Line Comments
// This is a single-line comment
# This is also a single-line comment
 2) Multiline Comments
/*
This is a multiple-lines comment block
that spans over multiple lines
*/
MASTER OF COMPUTER APPLICATION
7
Variable in PHP?
 Creating (Declaring) PHPVariables
 In PHP, all keywords like classes, functions, and user-defined functions are NOT
case-sensitive.
 In PHP, a variable starts with the $ sign, followed by the name of the variable:
 A variable name must start with a letter or the underscorecharacter.
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores(A-
z, 0-9, and _ )
 Variable names are case-sensitive .
 <?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
 MASTER OF COMPUTER APPLICATION
8
Variable in PHP?
 PHP Variables Scope
 In PHP, variables can be declared anywhere in the script.
 The scope of a variable is the part of the script where the variable can be
referenced/used.
 PHP has three different variable scopes:
1) local
2) global
3) static
 <?php
$x = 5; // global scope
function fun()
 {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
fun();
echo "<p>Variable x outside function is: $x</p>"; ?>
9 SINHGAD INSTITUTE OF MANAGEMENT MASTER OF COMPUTER APPLICATION
Variable in PHP?
 global Keyword in Php:
 The global keyword is used to access a global variable from within a
function.
 To do this, use the global keyword before the variables (inside the function):
 <?php
$x = 100;
$y = 200;
function fun()
 {
global $x, $y;
$y = $x + $y;
}
fun();
echo $y; // outputs 300
?>
10 MASTER OF COMPUTER APPLICATION
Variable in PHP?
 Static Keyword
 When a function is completed/executed, all of its variables are
deleted.
 Sometimes we want a local variable NOT to be deleted. We need it
for a further job.
 To do this, use the static keyword when you first declare the variable:

 <?php
static $x = 100;
echo $x;
?>

MASTER OF COMPUTER APPLICATION


11
echo and print statement
 PHP echo and print Statements:
➢ In PHP there are two basic ways to get output: echo and print.
➢ echo and print are more or less the same.
➢ They are both used to output data to the screen.
 Difference between echo & print
✓ echo has no return value while print has a return value of 1 so it can be used in
expressions.
✓ echo can take multiple parameters while print can take one argument.
✓ echo is marginally faster than print.
❑ The Syntax of echo
 <?php
echo "<h2>PHP is Fun!</h2>";
?>
❑ The Syntax of Print
 <?php
print "<h2>PHP is Fun!</h2>";
?>
12 MASTER OF COMPUTER APPLICATION

Operators in PHP
 PHP Operators
 Operators are used to perform operations on variables and values.
✓ Arithmetic operators
✓ Assignment operators
✓ Comparison operators
✓ Increment/Decrement operators
✓ Logical operators
✓ String operators
✓ Array operators

MASTER OF COMPUTER APPLICATION


13
Operators in PHP
 Arithmetic operators

<?php <?php <?php


$x = 100; $x = 400; $x = 25;
$y =200; $y =200; $y =20;
echo $x + $y; echo $x - $y; echo $x * $y;
?> ?> ?>
MASTER OF COMPUTER APPLICATION
14
Operators in PHP
➢ Assignment operators:
 Operator Name Example

= Assignment $x = $y

+= Addition $x += $y

-= Subtraction $x -= $y

*= Multiplication $x *= $y

/= Division $x /= $y

%= Modulus $x %= $y

== Equal $x==$y

MASTER OF COMPUTER APPLICATION


15
Operators in PHP
➢ Increment / Decrement operators
✓ The PHP increment operators are used to increment a variable's value.
✓ The PHP decrement operators are used to decrement a variable's value.

<?php <?php <?php <?php


$x = 100; $x = 100; $x = 100; $x = 100;
++$x; $x++; --$x; ++$x;
echo ++$x; echo ++$x; echo --$x; echo $x--;
?> ?> ?> ?>
MASTER OF COMPUTER APPLICATION
16
Operators in PHP
➢ Logical operators :
✓ The PHP logical operators are used to combine conditional statements.

<?php <?php
<?php <?php
$x = 100; $x = 100;
$x = 100; $x = 100;
$y=200; $y=200;
$y=200; $y=200;
echo $x && $y; echo $x || $y;
echo $x and $y; echo $x or $y;
?> ?>
?> ?>
SINHGAD INSTITUTE OF MANAGEMENT MASTER OF COMPUTER APPLICATION
17
Operators in PHP
➢ String data type operators:
✓ String data type operator are used to perform operation on string values.
✓ PHP has two operators that are specially designed for strings.

<?php
<?php
$txt1 =“Hello”;
$txt1 =“Hello”;
$txt2 =“World”;
$txt2 =“World”;
echo $txt1.= $txt2;
echo $txt1. $txt2;
?>
?>

MASTER OF COMPUTER APPLICATION


18
Function in PHP
➢ PHP Function :
✓ A function is a block of statements that can be used repeatedly in a
program.
✓ A function will not execute immediately when a page loads.
 A function will be executed by a call to the function.
✓ Inbuilt Function
✓ User Defined Function
✓ Inbuilt Function :
✓ There are several Inbuilt functions are available in php.
✓ Generally all its are single line functions.

MASTER OF COMPUTER APPLICATION


19
Function in PHP
 PHP Function :
✓ User Defined Function :
➢ A user defined function declaration starts with the word "function":
➢ Syntax
 function function_Name()
 {
code to be executed;
}
➢ Function names are NOT case-sensitive.
 <?php
function fun() {
echo "Hello world!";
}
fun(); // call the function
?>

MASTER OF COMPUTER APPLICATION


20
Operators in PHP
 PHP FunctionArguments:
✓ Information can be passed to functions through arguments. An argument is just like a
variable.
✓ Arguments are specified after the function name, inside the parentheses.
✓ If you want more than one arguments then give the ‘,’ operator between it.
 <?php
function details($fname)
 {
echo “Welcome $fname <br>";
}
details(“Sachin");
details(“Kapil");
?>

MASTER OF COMPUTER APPLICATION


21
Methods in PHP
✓ Methods in PHP:
 There are two ways the browser client can send information to the web server.
➢ GET Method
➢ POST Method
 Before the browser sends the information, it encodes it using a scheme called URL
encoding.
 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”.
✓ The GET method produces a long string that appears in your serverlogs.
✓ The GET method is restricted to send upto 1024 characters only.


MASTER OF COMPUTER APPLICATION
22
Methods in PHP
• Never use GET method if you 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.
<?php
if( $_GET["name"] )
{
echo "Welcome ". $_GET['name']. "<br />";
}
?>

MASTER OF COMPUTER APPLICATION


23
Methods in PHP
➢ POST Method
➢ The POST method transfers information via HTTPheaders.
➢ 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 securitydepends
on HTTP protocol.
➢ By using Secure HTTP you can make sure that your information is secure.
➢ The PHP provides $_POST associative array to access all the sent information
using POST method.
 <?php
 if( $_POST["name“] )
 {
 echo "Welcome ". $_POST['name']. "<br />";
 } ?>
MASTER OF COMPUTER APPLICATION
24
Methods in PHP
➢ Request Variable :
 The PHP $_REQUEST variable contains the contents of both $_GET,$_POST,
and $_COOKIE.
➢ The PHP $_REQUEST variable can be used to get the result from form data
sent with both the GET and POST methods.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] )
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>

MASTER OF COMPUTER APPLICATION


25
Session in PHP
 What is Session?
✓ Sessions are a simple way to store data for individual users against
a unique session ID.
✓ This can be used to persist state information between page
requests.
✓ Session IDs are normally sent to the browser via session, cookies
and the ID is used to retrieve existing session data.
✓ A session is a way to store information (in variables) to be used
across multiple pages.
 <?php
 // Set session variables
 $_SESSION[“session_object"] = “Value";
 $_SESSION["favfruits"] = "Apple";
 ?>
26
Session in PHP
 Assigning session in PHP
 echo “Session is " . $_SESSION[“session_objectname"] ;
 echo "Favorite Fruit is " . $_SESSION["favfruits"] ;
 Session Destroy in PHP
 session_destroy() : This function does not need any argument and a single call can
destroy all the session variables.
 unset():
 If you want to destroy a single session variable then you can use unset() function to
unset a session variable.
 <?php
 // remove all session variables
 session_unset();
 // destroy the session
 session_destroy(); ?>

MASTER OF COMPUTER APPLICATION
27
Cookies in PHP
 What is Cookies?
✓ 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 also.
✓ A cookie is created with the setcookie() function.
✓ Syntax of Cookies…
✓ setcookie(name, value, expire, path, domain, secure, httponly);

MASTER OF COMPUTER APPLICATION


28
Cookies in PHP
 Difference between Session and Cookies.

MASTER OF COMPUTER APPLICATION


29
Cookies in PHP
 Difference between Session and Cookies.
Cookies Sessions
It is not holding the multiple variable
It is holding the multiple variable in sessions.
in cookies.

we can accessing the cookies values in we cannot accessing the session values in
easily. So it is less secure. easily. So it is more secure.

setting the cookie time to expire the using session_destory(), we we will destroyed
cookie. the sessions.

The session_start() function must be the very


The setcookie() function must appear
first thing in your document. Before any
BEFORE the <html> tag.
HTML tags.

MASTER OF COMPUTER APPLICATION


30
Form in PHP
❑ Form
✓ To make web pages interactive, the concept of forms was
developed.
✓ Forms become one of the most important tools for making web
pages dynamic.
✓ Forms enable users to interact with the web server by entering data
in the fields on the screen displayed by the web page at the client.
✓ This technology allows a web page to contain empty areas in which
the user can enter information .
✓ After the user fills information in these blank fields, the browser
sends this information to the web server requesting for another web
page.

MASTER OF COMPUTER APPLICATION
31
Form in PHP
✓ Forms allow actual data inputs which can initiate different
processing.
The HTML code for Forms
<HTML>
<HEAD> <TITLE> A demo of Forms technology
</TITLE></HEAD>
<FORM Method=“POST” Action=“name.asp”>
<Input Type=“text” Name=“T1” Size=“20”>
<Input Type=“Submit” Value=“Submit” Name=“B1”>
</FORM>
</HTML>

MASTER OF COMPUTER APPLICATION
32
Database Connection
❖ Database connectivity in PHP.
 There are three ways to connect Database in php
 MYSQL
 MYSQLI
 PDO
 Mysql used to connect database using procedure.
 Mysqli and PDO Both are object-oriented, but MySQLi also offers a
procedural API.
 PDO will work on 12 different database systems.
 Whereas MySQLi will only work with MySQL databases.

MASTER OF COMPUTER APPLICATION


33
Database Connection
❖ Database connectivity in PHP.
❖ Define constant variables DB_HOST, DB_NAME, DB_USER,
DB_PASSWORD .
❖ Define variable $variable_name which is for connection of database
✓ call function
✓ mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) and
die("Failed to connect to MySQL: " . mysql_error());
 if connected then Select Database.
✓ $con=mysql_connect(DB_HOST, B_USER,DB_PASSWORD)
✓ $db= mysql_select_db(" DB_NAME ",$con);
✓ $query=mysql_query("YOUR_MYSQL_QUERY",$db);
✓ echo mysql_result($query, 2);
✓ mysql_close($link);
34 MASTER OF COMPUTER APPLICATION

File Handling
 File handling is an important part of any web application.
 You often need to open and process a file for different tasks.
 Opening a file
 Reading a file
 Writing a file
 Closing a file
 Opening and Closing Files
 The PHP fopen() function is used to open a file.
 It requires two arguments stating first the file name and then mode in
which to operate.
 If an attempt to open a file fails then fopen returns a value of false otherwise it returns a
file pointer
MASTER OF COMPUTER APPLICATION
35
File Handling
Mode Purpose

r Opens the file for reading only.


Places the file pointer at the beginning of the file.
r+ Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
Opens the file for writing only.
Places the file pointer at the beginning of the file.x
w and truncates the file to zero length. If files does not
exist then it attempts to create a file.
Opens the file for reading and writing only.
w+ Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
MASTER OF COMPUTER APPLICATION
36
File Handling
Mode Purpose
Opens the file for writing only.
a Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
Opens the file for reading and writing only.
a+ Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
fclose():
After making a changes to the opened file it is important to close it
with the fclose() function.
Filesize():
The files length can be found using the filesize() function.
It takes the file name as its argument and returns the size of the file
expressed in bytes.
MASTER OF COMPUTER APPLICATION
37
File Handling
<?php
$filename = "D:/Xampp/htdocs/Myweb/newfile.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo"</br>";
echo ( "$filetext" );
echo"</br>";
echo("file name: $filename");
?>
MASTER OF COMPUTER APPLICATION
38
Exception & Error Handling
➢ What is Error Handling?
➢Error handling is the process of catching errors raised by program
and then taking appropriate action.
➢ Its very simple in PHP to handle an errors.
➢An error message with filename, line number and a message
describing the error is sent to the browser.
➢ What is an Exception?
✓ An error is an unexpected program result that cannot be handled by
the program itself.
✓ Errors are resolved by fixing the program.
✓An example of an error would be an infinite loop that never stops
executing.
✓ Examples of exception include trying to open a file that does not exist.
MASTER OF COMPUTER APPLICATION
39
Exception & Error Handling
➢ Why handle exception?
➢Avoid unexpected results on our pages which can be very
annoying or irritating to our end users.
➢Improve the security of our applications by not exposing
information which malicious users may use to attack our
applications.
➢ Php Exceptions are used to change the normal flow of a program
if any expected error occurs.

MASTER OF COMPUTER APPLICATION


40
PHP Error Handling
➢ PHP Error handling
✓ Following are different error handling methods:
❑ Simple "die()" statements
❑ Custom errors and error triggers
❑ Error reporting
✓ PHP offers a number of ways to handle errors.
➢ Die statements:
✓ The die function combines the echo and exit function in one.
✓It is very useful when we want to output a message and stop the
script execution when an error occurs.
➢ Custom error handlers :
✓ These are user defined functions that are called whenever an
error occurs.
MASTER OF COMPUTER APPLICATION
41
PHP Error Handling
<?php
$file=fopen(“student_information.txt","r");
?>
❑ If the file does not exist you might get an error like this:

Warning: fopen(student_information.txt) [function.fopen]: failed to open stream:


No such file or directory in D:\Myweb\AIT\student_info.php on line 5

MASTER OF COMPUTER APPLICATION


42
die() function
To prevent the user from getting an error message like the one above, we test
whether the file exist before we try to access it:

<?php
if(!file exists("student_information.txt "))
{
die("File not found");
} else {
$file=fopen(" student_information.txt ","r");
}
?>

MASTER OF COMPUTER APPLICATION


43
Creating a Custom Error Handler
➢ Create a special function that can be called when an error

occurs in PHP.
➢ This function must be able to handle a minimum of two
parameters (error level and error message) but can accept up
to five parameters

➢ (optionally: file, line-number, and the error context):

error_function(error_level, error_message,
error_file, error_line, error_context)

MASTER OF COMPUTER APPLICATION


44
Creating a Custom Error Handler

Parameter Description
Required. Specifies the error message for the user-
error_message
defined error
Optional. Specifies the filename in which the
error_file
error occurred
Optional. Specifies the line number in which the
error_line
error occurred
Optional. Specifies an array containing every
error_context variable, and their values, in use when the error
occurred

MASTER OF COMPUTER APPLICATION


45
Exception & Error Handling
➢PHP Error handling
PHP error reporting :
✓ The error message depending on your PHP error reporting
settings.
✓This method is very useful in development environment when
you have no idea what caused the error.
✓ The information displayed can help you debug your application.

<?php
error_reporting($reporting_level);
?>

MASTER OF COMPUTER APPLICATION


46
Exception & Error Handling
➢ Difference between Errors and Exception
✓Exceptions are thrown and intended to be caught while errors are
generally irrecoverable.
✓ Exceptions are handled in an object oriented way.
✓ This means when an exception is thrown;
✓ An exception object is created that contains the exception details.

MASTER OF COMPUTER APPLICATION


47
Exception & Error Handling
Mthod Description Example
getMessage() Displays the exception’s <?php
message echo $e->getMessage();
?>
getCode() Displays the numeric code that <?php
represents the exception echo $e->getCode(); ?>
getFile() Displays the file name and path <?php
where the exception occurred echo $e->getFile(); ?>
getLine() Displays the line number where <?php
the exception occurred echo $e->getLine(); ?>
getTrace() Displays an array of the <?php
backtrace before the exception print_r( $e->getTrace()); ?>

MASTER OF COMPUTER APPLICATION


48
Exception & Error Handling
❑ Try:
✓ A function using an exception should be in a "try" block.
✓ If the exception does not trigger, the code will continue as
normal.
✓If the exception triggers, an exception is "thrown".
❑ Throw :
✓ This is how you trigger an exception.
✓ Each "throw" must have at least one "catch".
❑ Catch :
✓A "catch" block retrieves an exception and creates an object
containing the exception information.

MASTER OF COMPUTER APPLICATION


49
Exception & Error Handling
<?php
try
{
//code goes here that could potentially throw an exception
}
catch (Exception $e)
{
//exception handling code goes here
}
?>

MASTER OF COMPUTER APPLICATION


50
Exception & Error Handling

MASTER OF COMPUTER APPLICATION


50

You might also like