0% found this document useful (0 votes)
22 views39 pages

Unit 5

This document provides an outline and introduction to server-side scripting with PHP. It discusses PHP basics like variables, data types, operators, and control structures. It also covers arrays, functions, form processing, file handling, and sessions. The goal is to teach the fundamentals of PHP for use in server-side web programming. Sample code is provided to demonstrate PHP syntax and basic programming concepts.

Uploaded by

Jay Mangukiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views39 pages

Unit 5

This document provides an outline and introduction to server-side scripting with PHP. It discusses PHP basics like variables, data types, operators, and control structures. It also covers arrays, functions, form processing, file handling, and sessions. The goal is to teach the fundamentals of PHP for use in server-side web programming. Sample code is provided to demonstrate PHP syntax and basic programming concepts.

Uploaded by

Jay Mangukiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Web Programming (WP)

GTU # 3160713

Unit-05
Server Side
Scripting with
PHP
Prof. Vijay M Shekhat
Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9558045778
 Outline
Looping

 Introduction to PHP  String Functions


 Basics of PHP  Form Processing
 Variables  File Uploadig
 Array  File Handling
 Function  Exception Handling
 Browser Control  Date and Time zone
 Browser Detection  Cookie / Session
Introduction
 PHP is a scripting language that allows you to create dynamic Web pages
 You can embed PHP scripting within normal html coding
 PHP was designed primarily for the Web
 PHP includes a comprehensive set of database access functions
 High performance/ease of learning/low cost
 Open-source
 Anyone may view, modify and redistribute source code
 Supported freely by community
 Platform independent

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 3
Basics of PHP
 PHP files end with .php, you may see .php3 .phtml .php4 as well
 PHP code is contained within tags
<?php ?> or
Short-open: <? ?>
 HTML script tags: (This syntax is removed after PHP 7.0.0)
<script language="php"> </script>
 Comments
// for single line
/* */ for multiline

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 4
PHP Basic Example
7 <?php
8 $name = "Vijay Shekhat";
Scripting delimiters
// declaration
9 ?>
Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12 <head> Single-line comment
13 <title>Untitled document</title>
14 </head>
15
16 <body style = "font-size: 2em">
17 <p>
18 <strong>
19
20 <!-- print variable name’s value -->
21 Welcome to PHP, <?php print( "$name" ); ?>!
22 </strong>
23 </p> Function print outputs the value of
24 </body> variable $name
25 </html>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 5
Variables
 All variables begin with $ and can contain letters, digits and underscore (variable name can
not begin with digit)
 PHP variables are Case-sensitive
 Don’t need to declare variables
 The value of a variable is the value of its most recent assignment
 Variables have no specific type other than the type of their current value
 Can have variable variables $$variable (not recommended)
Example : $a = “b”;
$b = “Vijay Shekhat”;
echo($$a);

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 6
Variables (Cont.)
 Variable names inside strings replaced by their value
Example : $name = “Vijay Shekhat”;
$str = “My name is $name”;
 Type conversions
 settype function Data Type Description
<?php int, integer Whole numbers (i.e., numbers without a decimal point).
$b = 32; // integer float, double Real numbers (i.e., numbers containing a decimal point).
settype($b, "string");
string Text enclosed in either single ('') or double ("") quotes.
?>
bool, boolean True or false.
 Type casting
array Group of elements.
<?php object Group of associated data and methods.
echo (int)12.5; // 12
?> resource An external data source.
NULL No value.
 Concatenation operator
 . (period)

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 7
Variables Scope
 Scope refers to where within a script or program a variable has meaning or a value
 Mostly script variables are available to you anywhere within your script.
 Note that variables inside functions are local to that function and a function cannot access
script variables which are outside the function even if they are in the same file.
 The modifiers global and static allow function variables to be accessed outside the function
or to hold their value between function calls respectively

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 8
Decision Making Statements
 Simple if statement.
 If else statement.
 Else if ladder statement.
 Nested if statement.
 Switch statement.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 9
Loops
 While loop.
 Do while loop.
 For loop.
 Foreach loop.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 10
PHP Arrays
 Array is a group of variable that can store multiple values under a single name.
 In PHP, there are three types of array.
 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.
 Associative Array
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.
 Multidimensional Array
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.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 11
PHP Arrays (Example)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8 <head>
9 <title>Array manipulation</title>
10 </head>
11
12 <body>
13 <?php Create the array $first by assigning a
14
value to an array element.
15 // create array first
16 print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
19
Assign a value to the array, omitting the
$first[ 1 ] = "one";
20 $first[ 2 ] = "two";
Use a for
index. Appends loop
a new to printtoout
element theeach
end element’s index and
21 $first[] = "three";
22
value. Function count returns the total number of
of the array.
23 // print elements
each element’s index in the array.
and value
24 for ( $i = 0; $i < count( $first ); $i++ )
25 print( "Element $i is $first[$i] <br />" );

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 12
PHP Arrays (Example) (cont.)
27 print( "<br /><strong>Creating the second array
28 </strong><br />" ); Call function array to create an array that
29 contains the arguments passed to it. Store the
30 // call function array to create array second
array in variable $second.
31 $second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print( "Element $i is $second[$i] <br />" );
34
35 print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values to non-numerical indices
39
Assign values to non-numerical
$third[ "ArtTic" ] = 21;
40 $third[ "LunaTic" ] = 18;
indices in array $third.
41 $third[ "GalAnt" ] = 23;
42
Function reset sets the internal pointer to
43 theelements
// iterate through the array first element of each
and print the array.
44 // element’s name and value
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 Function key returns the index of the element
print( "$element is $third[$element] <br />" );
Function
which thenext moves
internal the internal
pointer pointer to the next
references.
element.
Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 13
PHP Arrays (Example) (cont.)
49 print( "<br /><strong>Creating the fourth array
50 </strong><br />" );
51
52 // call function array to create array fourth using
53 // string indices
54 $fourth = array(
55 "January" => "first", "February" => "second",
56 "March" => "third", "April" => "fourth",
57 "May" => "fifth", Operator
"June" =>=>is"sixth",
used in function array to assign
58 "July" => each
"seventh", element
"August" => a"eighth",
string index. The value to the left
59 "September" => "ninth", of"October"
the operator is the array index, and the value to
=> "tenth",
60 "November" =>
the right is the element’s value.
"eleventh","December" => "twelfth"
61 );
62
63 // print each element’s name and value
64 foreach ( $fourth as $element => $value )
65 print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 14
PHP Array Functions
 count($array) / sizeof($array)
Count all elements in an array, or something in an object
 array_shift($array)
Remove an item from the start of an array and shift all the numeric indexes
 array_pop($array)
Remove an item from the end of an array and return the value of that element
 array_unshift($array,”New Item”)
Adds item at the beginning of an array
 array_push($array,”New Item”)
Adds item at the end of an array

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 15
PHP Array Functions (cont.)
 sort($array [, $sort_flags])
 Array can be sorted using this command, which will order them from the lowest to highest
 If there is a set of string stored in the array they will be sorted alphabetically.
 The type of sort applied can be chosen with the second optional parameter $sort_flags which can be
 SORT_REGULAR compare items normally (don’t change type)
 SORT_NUMERIC compare items numerically
 SORT_STRING compare items as string
 SORT_LOCALE_STRING compare items as string, based on the current locale
 rsort($array [, $sort_flags])
 It will sort array in reverse order (i.e. from highest to lowest)
 shuffle($array)
It will mix items in an array randomly.
 array_merge($array1,$array2)
It will merge two arrays.
 array_slice($array,$offset,$length)
returns the sequence of elements from the array $array as specified by the $offset and $length parameters.
Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 16
PHP Functions
 A function is a piece of code which takes zero or more input in the form of parameter and
does some processing and returns a value.
 Creating PHP function
Begins with keyword function and then the space and then the name of the function then parentheses”()” and
then code block “{}”
<?php
function functionName()
{
//code to be executed;
}
?>

Note: function name can start with a letter or underscore "_", but not a number!

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 17
PHP Functions (Cont.)
 Where to put the function implementation?
In PHP a function could be defined before or after it is called.

<?php <?php
function functionName() functionName();
{
//code to be executed; function functionName()
} {
Here function call to
//code is be
before
executed;
functionName(); implementation,
} which is also valid
?> ?>

Here function call is after


implementation, which is valid

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 18
Browser Control
 PHP can control various features of a browser.
 This is important as often there is a need to reload the same page or redirecting the user to
another page.
 Some of these features are accessed by controlling the information sent out in the HTTP
header to the browser, this uses the header() command such as :
header(“Location: index.php”);
 We can also control the caching using same header() command
header(“Cache-Control: no-cache”);
Or can specify the content type like,
header(“Content-Type: application/pdf”);

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 19
Browser Detection
 The range of devices with browsers is increasing so it is becoming more important to know
which browser and other details you are dealing with.
 The browser that the server is dealing can be identified using:
$browser_ID = $_SERVER[‘HTTP_USER_AGENT’];
 Typical response of the above code is follows:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/56.0.2924.87
 which specifies that user is using Chrome browser and windows 10 OS with 64 bit
architecture

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 20
PHP String Functions
 Most of the time in PHP we suppose to do manipulation of strings, wheatear it be input from
the user, databases or files that have been written.
 String can be think as a array of characters, so it is possible to do something like this,
$mystring = “Welcome to Darshan College of Engineering”;
print ($mystring[11]) ; // which will print ‘D’
 This uses an index as an offset from the beginning of the string starting at 0
 Often, there are specific things that need to be done to a string, such as reversing, extracting
part of it, finding a match to part or changing case etc..

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 21
PHP String Functions (Cont.)
String Function Purpose
strlen($string) Returns length of string.
strstr($str1,$str2) Finds str2 inside str1 (returns false if not
found or returns portion of string1 that
contains it)
strpos($str1,$str2) Finds str2 inside str1 and returns index.
str_replace($search,$replace,$str,$count) Looks for $search within $str and replaces
with #replace, returning the number of times
this is done in $count
substr($string,$startposition,$length) Returns string from either start position to
end or the section given by $startpos to
$startpos+$length
trim($string) Trims away white space, including tabs,
rtrim($string) newlines and spaces, from both beginning
ltrim($string) and end of a string. ltrim is for the start of a
string only and rtrim for the end of a string
only

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 22
PHP String Functions (Cont.)
String Function Purpose
strip_tags($string,$tagsallowed) Strips out HTML tags within a string, leaving
only those within $tagsallowed intact
stripslashes($string) Strips out inserted backslashes
explode($delimiters,$string) It will breaks $string up into an array at the
points marked by the $delimiters
implode($glue,$array) Function returns combined string from an
array.
strtolower($string) Converts all characters in $string to
lowercase.
strtoupper($string) Converts all characters in $string to
uppercase.
ucword($string) Converts all the first letters in a string to
uppercase.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 23
Form Processing
 We can access form data using inbuilt PHP associative array.
 $_GET => in case we have used get method in the form
 $_POST => in case we have used post method in the form
 $_REQUEST => in both the cases

 For example,
html recive.php
<form action=“recive.php” method=“get”> <?php
<input type=“text” name=“UserName”> $u = $_GET[‘UserName’];
<input type=“submit”> echo($u);
</form> ?>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 24
File uploads
<!DOCTYPE html>
<html>
<body>
<form action=“con_upload.php" method="post" enctype="multipart/form-data">
Select Profile Picture to upload: <input type="file" name="profilepic">
<input type="submit" value="Upload Profile Picture" name="submit">
</form>
</body>
</html>

// con_upload.php
<?php
move_uploaded_file($_FILES['profilepic']['tmp_name'], './uploads/'. $_FILES['profilepic']
['name']);
?>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 25
Regular Expression
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with another string

<?php <?php
$str = "Darshan University"; $str = "Darshan College, Darshan University";
$pattern = "/darshan/i"; $pattern = "/darshan/i";
echo preg_match($pattern, $str); echo preg_match_all($pattern, $str);
?>
?> //Output: 2
//Output: 1
<?php
$str = "Darshan College";
$pattern = "/College/";
echo preg_replace($pattern, "University", $str);
?>
//Output: "Darshan University"
Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 26
File Handling in PHP
 PHP has several functions for creating, reading, uploading, and editing files.
 fopen($filename, $mode) will return the handle to access file.
 "r" (Read only. Starts at the beginning of the file)
 "r+" (Read/Write. Starts at the beginning of the file)
 "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
 "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)
 "a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
 "a+" (Read/Write. Preserves file content by writing to the end of the file)

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 27
File Handling in PHP (Cont.)
Function Purpose
file_exists($file) Will return true if file is found, false
otherwise
filesize($file) Returns the size of the file in bytes.
fread($file,$bytesToRead) Will read $bytesToRead from $file handle
fwrite($file,$str) Will write $str in the $file handle
fclose($file) Will close the $file handle
copy($source,$destination) Will copy from $source to $destination
rename($oldname,$newname) Will rename the file to $newname
unlink($file) Will delete the file

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 28
File Handling Example

text.txt
Hello World From Darshan College

Read File
<?php
$file = fopen("text.txt","a+");
$text = fread($file,filesize("text.txt"));
echo($text);
?>
Write File
<?php
fwrite($file," New Content");
$file = fopen("text.txt","a+");
$text = fread($file,filesize("text.txt"));
echo($text);
?>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 29
Exception Handling
<?php
try{
echo ("<br>".myFunction(5, 3));
echo ("<br>".myFunction(5, 0));
}
catch(Exception $e) {
echo("<br>Message: ".$e->getMessage());
}
finally{
echo("<br>This will always execute");
}

function myFunction($a, $n){


if ($n == 0) {
throw new Exception("Divide by zero exception", 2);
}
$ans = $a / $n;
return $ans;
}
?>
Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 30
Date and Time zone
 Calculate Number of days left in your next birthday.
<?php
$dob = new DateTime("1990-02-29");
$currentDate = new DateTime(date("Y-m-d"));

$dobNew = date_create(date_format($dob,date("Y")."-m-d"));

if($currentDate > $dobNew)


{
date_add($dobNew, date_interval_create_from_date_string('1 year'));
}

$dateDiff= date_diff($dobNew,$currentDate);

echo("Days left in your next birthday: " . $dateDiff->days . "days");


?>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 31
Cookies in PHP
 Without Cookie

Entered Username & Password and sends HTTP Request


Server gives HTTP Response containing the home page

User Sends HTTP Request for some other page


Server
Server does not recognize who the user as its stateless protocol

 With Cookie

Entered Username & Password and sends HTTP Request


Server gives HTTP Response with home page & cookie

User Sends HTTP Request for some other page + cookie


Server
Server will identify the user from the cookie & gives response

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 32
Cookies in PHP (Cont.)
 HTTP cookies are data which a server-side script sends to a web client to keep for a period of
time.
 On every subsequent HTTP request, the web client automatically sends the cookies back to
server (unless the cookie support is turned off).
 The cookies are embedded in the HTTP header (and therefore not visible to the users).
 Shortcomings/disadvantages of using cookies to keep data
 User may turn off cookies support.
 Users using the same browser share the cookies.
 Limited number of cookies (~20) per server/domain and limited size (~4k bytes) per cookie
 Client can temper with cookies

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 33
Cookies in PHP (Cont.)
 To set a cookie, call setcookie()
 e.g., setcookie('username', ‘Vijay');
 To delete a cookie (use setcookie() without a value)
 e.g., setcookie('username');
 To retrieve a cookie, refer to $COOKIE
 e.g. $username = $_COOKIE['username‘];
 Note :
 Cookies can only be set before any output is sent.
 You cannot set and access a cookie in the same page. Cookies set in a page are available only in the future
requests.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 34
Cookies in PHP (Cont.)
setcookie(name, value, expiration, path, domain, secure)
 Expiration
 Cookie expiration time in seconds
 0  The cookie is not to be stored persistently and will be deleted when the web client closes.
 Negative value  Request the web client to delete the cookie
 e.g.: setcookie('username', 'Joe', time() + 1800); // Expire in 30 minutes
 Path
 Sets the path to which the cookie applies. (Default is ‘/’)
 Domain
 The domain that the cookie is available.
 Secure
 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.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 35
Session in PHP
 PHP Session is a way to make data accessible across the various pages of an entire website.
 A session creates a file in a temporary directory on the server where registered session
variables and their values are stored.
 The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.
 When a session is started following things happen
 PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal
numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's computer to store unique session
identification string.
 A file is automatically created on the server in the designated temporary directory and bears the name of
the unique identifier prefixed by sess_, sess_3c7foj34c3jj973hjkop2fc937e3443.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 36
Starting a PHP Session
 A PHP session is easily started <?php
by making a call to the session_start();
session_start() function. if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
 This function first checks if a }else {
session is already started and if $_SESSION['counter'] = 1;
}
none is started then it starts one.
$msg = "You have visited this page ".
 It is recommended to put the $_SESSION['counter'];
call to session_start() at $msg .= "in this session.";
?>
the beginning of the page. <html><head>
 The following example starts a <title>Setting up a PHP session</title>
session then register a variable </head><body>
<?php echo ( $msg ); ?>
called counter that is </body></html>
incremented each time the page
is visited during the session.

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 37
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.
Logout.php
<?php
session_destroy();
?>

 If you want to destroy a single session variable then you can use unset() function to unset
a session variable.
Logout.php
<?php
unset($_SESSION[‘counter’]);
?>

Prof. Vijay M Shekhat #3160713 (WP)  Unit 05 – Server Side Scripting with PHP 38
Web Programming (WP)
GTU # 3160713

Thank
You

Prof. Vijay M. Shekhat


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9558045778

You might also like