Sie sind auf Seite 1von 81

PHP

Sanjay P. Bhakkad
Associate Professor
IMSCD&R Ahmednagar
PHP : Introduction
 PHP stands for HyperText Preprocessor.
 PHP is an interpreted language, i.e. there is no need for
compilation.
 PHP is a server side scripting language.
 PHP is faster than other scripting language e.g. asp and jsp.
 PHP is a powerful tool for making dynamic and interactive
Web pages.
 PHP is a widely-used, free, and efficient.
 PHP scripts can only be interpreted on a server that has PHP
installed. The client computers accessing the PHP scripts
require a web browser only.
 A PHP file contains PHP tags and ends with the extension
".php".
2 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP: Features
 Performance:
 Script written in PHP executes much faster then those scripts
written in other languages such as JSP & ASP.
 Open Source Software:
 PHP source code is free available on the web, you can developed all
the version of PHP according to your requirement without paying
any cost.
 Platform Independent:
 PHP are available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily
executed in other OS also.
 Compatibility:
 PHP is compatible with almost all local servers used today like
Apache, IIS etc.
 Embedded:
 PHP code can be easily embedded within HTML tags and script.
3 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP: Installation
 To install PHP, we will suggest you to install AMP (Apache,
MySQL, PHP) software stack. It is available for all
operating systems. There are many AMP options available
in the market that are given below:
 WAMP for Windows
 LAMP for Linux
 MAMP for Mac
 SAMP for Solaris
 FAMP for FreeBSD
 XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross
Platform: It includes some other components too such as
FileZilla, OpenSSL, Webalizer, OpenSSL, Mercury Mail etc.

4 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP and the Web Server Architecture

5 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP and the Web Server Architecture
 The numbers used below beside the Label names following 1 for Request flow and 2 for
response flow.
A1: First user accessed the website through browser. That means user types the URL of the
website in browser and hit go.
B1: The page request on browser will reach to the Web Server (Apache).
C: Web server will collect that requested page (HTML or PHP or Image file etc) from its
document root. (In this example it is www folder in WAMP. You may have it at other place.)
B2: Now if it is a static element like HTML , CSS , image file or Java Script file then Apache will
send it directly to browser.
A2: And Browser will render it to user on screen
D1 : If it is a PHP file then Apache sends the content of the file to PHP Interpreter. PHP
interpreter interprets the PHP code and executes it.
 If database operation is required it performs the same (E)
D2: PHP Interpreter generates output (if the PHP code is to generate any output) and sends
to Apache
B2: Apache sends that content to browser
A2: Browser renders it to users' screen
6 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP and the Web Server Architecture
 All static components like HTML, CSS files, Image Files, Java
Scripts etc doesn't need interpreter. Current web browsers
are built to render them and display on screen properly. That is
why if user requests for these kind of components Apache
collects them from Document root and sends back to
Browser directly; and known as client side components.
 Only if requested page is a PHP page Apache will send it to
PHP interpreter to get it translated and executed. Hence
known as server side components.
 PHP files are kept on Server (in Document root) - Server
Side
 PHP Interpreter interprets PHP language and executes
instructions as per code. - Scripting language

7 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Model, Overview of PHP Capabilities
 PHP is a server-side interpreter which is Open Source
and free
 PHP provides familiar syntax to C, Perl and Java
developers
 PHP has fast connections to popular databases including
open source database like MySQL
 PHP runs reliably on Windows, Linux and Mac servers
and clients as well as on all the popular browsers.
 PHP's associative arrays are very useful for UI and
database apps
 PHP's object oriented classes are easy to understand
 PHP has capabilities for linking to PDF, SWF, XML, Java, etc
8 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Handlers
 Web servers are designed to send static resources including
HTML, images, etc to users. They are not designed to interpret
any code by themselves. Hence they need another program to
do it for them.
 PHP handlers are the programs that interpret the PHP code in
your web application and process it to be sent as HTML (or
another static format) by your web server.
 Currently there are 4 major PHP handlers available on Apache.
 These include mod_php (AKA DSO), CGI, FastCGI, and suPHP.
 Each of these handle memory, CPU, and file permissions in a
different way which can then manifest itself in your web app in
everything from performance to important features of your
application.

9 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


mod_php (DSO)
 DSO (which is short for Dynamic Shared Object) or mod_php
is the oldest and, some would say, the fastest PHP handler
available.
 This is the default handler for your Apache web server.
 It has a very low CPU and memory requirement which may be
beneficial in situations where computing resources are limited.
 The major drawback of mod_php is that it runs as part of
Apache which means that it runs as the same user that your
Apache process runs. Hence it must have permissions to all of
your files.
 Then, if your machine is compromised by an attacker that
attacker could have access to each and every thing in your
website as well as for every site hosted on your machine.

10 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


CGI
 CGI is the fallback in most servers when mod_php is not
available. Instead of running the PHP code within Apache
it is now run as it’s own CGI process, that is, in a program
outside of your Apache server.
 Unlike mod_php however CGI has the ability to see the
PHP as another user (presumably the user that owns the
files) using another Apache module known as suexec.
 For performance CGI is not nearly as fast as mod_php
and requires more CPU time. It is however still soft on
memory usage which may be a benefit to some users.

11 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


CGI vs. Shared Object etc.

Criteria mod_php CGI suPHP FastCGI


Memory usage Low Low Low High
CPU Usage Low High High Low
Security Low Low High High
Run as file owner No No Yes Yes

Overall
Fast Slow Slow Fast
Performance

12 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP HTML Embedding Tags and Syntax
 PHP is an HTML-embedded server-side scripting language.
 PHP in HTML:
 In an HTML page, PHP code is enclosed within special
PHP tags. When a visitor opens the page, the server
processes the PHP code and then sends the output (not
the PHP code itself) to the visitor's browser.
 Note: When a given file contains PHP code, it must have
a PHP extension. In most cases this is “.php”.

13 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP in HTML code
<html>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>

<?php
//your php code here
?>

<b>Here is some more HTML</b>

<?php
//more php code
?>

</body>
</html> File: phpInHtmlEx.php
14 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP in HTML using short_open_tag
 If you want to shorten your code as much as possible, you can
go for the short_tags option.
 This will save you from typing <?php at the beginning of the
code, shortening it to just <?.
 In order to enable this, you should update the php.ini file and
turn the "short_tags" setting from "Off" to "On".
 While on most servers this setting is already turned on, it's
always best to check beforehand.
 A problem that can occur if using short tags is a conflict with
the XML usage. For XML, the <? syntax will start a processing
function.
 To avoid this problem, the alternative <?= tag can be used.

15 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP in HTML using short_open_tag
<html>
<head></head>
<body>
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html>

 Note: If you want to build a website compatible with as


many platforms as possible, you should not rely on
short_tags.
File: shortTagEx.php
16 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
HTML in PHP using echo
 <?php
echo "<html>";
echo "<head></head>";
echo "<body">";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here
echo "</body>";
echo "</html>";
?> File: htmlInPhp.php

 Following code outputs 100 <br /> tags.


 <?php for($i=0; $i<100; $i++) { ?>
<br />
<?php } ?>
File: htmlInPhpEx1.php
17 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Simple PHP script
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<?php
echo '<p>This content was generated by PHP</p>';
?>
<p>And this content is static HTML</p>
</body>
</html> File: firstPhp.php

18 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Basic PHP Syntax
 A PHP script can be placed anywhere in the document.
 A PHP script starts with <?php and ends with ?>
 The default file extension for PHP files is ".php".
 A PHP file normally contains HTML tags, and some PHP
scripting code.
 PHP statements end with a semicolon (;).
 In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-
sensitive.
 However; all variable names are case-sensitive.

19 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP supports several ways of commenting:
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>
File: commentsEx.php
20 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Variables
 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 File: variableEx.php

<?php Note: When you assign a text value to


$txt = "Hello world!"; a variable, put quotes around the value.
Note: Unlike other programming
$x = 5;
languages, PHP has no command for
$y = 10.5; declaring a variable. It is created the
?> moment you first assign a value to it.
21 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Variables
 PHP is a Loosely Typed Language
 We did not have to tell PHP which data type the variable is.
 PHP automatically converts the variable to the correct data type,
depending on its value.
 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:
 Global : A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function.
 Local : A variable declared within a function has a LOCAL SCOPE and
can only be accessed within that function.
 Static : Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local variable NOT
to be deleted, and should retain its value for a further job. To do this, use
the static keyword when you first declare the variable.
 The global keyword is used to access a global variable within a function.
File: globalVarEx.php, localVarEx.php, globalKeywordEx.php, staticKeywordEx.php
22 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP echo and print Statements
 Both used to output data to the screen
 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.
 Both statements can be used with or without parenthesis.
<?php <?php
echo "<h2>PHP is Fun!</h2>"; print "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>"; print "Hello world!<br>";
echo "Message", "with", print "I'm about to learn
"multiple parameters."; PHP!";
?> ?> File: echoAndPrintEx.php
23 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Display Variables using echo and print
 <?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
 <?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?> File: echoAndPrintEx1.php
24 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Data Types
 Variables can store data of different types, and different
data types can do different things.
 PHP supports the following data types:
 String
 Integer
 Float (or double)
 Boolean
 Array
 Object
 NULL
 Resource

25 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP String
 A string is a sequence of characters, like "Hello world!".
 A string can be any text inside quotes.You can use single
or double quotes:
 <?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

26 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Integer
 An integer data type is a non-decimal number between:
-2,147,483,648 and 2,147,483,647.
 Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based -
prefixed with 0)
 In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
 <?php
$x = 5985;
var_dump($x);
?>

27 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Float PHP Boolean
 A float (floating point  A Boolean represents two
number) is a number with a possible states: TRUE or
decimal point. FALSE.
 In the following example $x  Booleans are often used in
is a float. conditional testing.
 The PHP var_dump()  The PHP var_dump()
function returns the data function returns the data
type and value: type and value:
 <?php  <?php
$x = 10.365; $x = true;
var_dump($x); $y = false;
?> var_dump($x);
var_dump($y);
?>
28 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Object
 An object is a data type which stores data and information on how
to process that data.
 In PHP, an object must be explicitly declared.
 First we must declare a class of object. For this, we use the class
keyword. A class is a structure that can contain properties and
methods:
 <?php
class Car {
function Car() {
$this->model = "LXi";
}
}
$WagonR = new Car(); // create an object
echo $WagonR->model; // show object properties
?>

29 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP NULL Value
 Null is a special data type which can have only one value:
NULL.
 A variable of data type NULL is a variable that has no
value assigned to it.
 Note: If a variable is created without a value, it is
automatically assigned a value of NULL.
 We can empty the variable, by setting the value to NULL:
 <?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

30 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Array PHP Resource
 An array stores multiple  The special resource type
values in one single is not an actual data type.
variable. It is the storing of a
 In the following example reference to functions and
$cars is an array. resources external to PHP.
 <?php  A common example of
$cars using the resource data
= array("Volvo","BMW", type is a database call.
"Toyota");
var_dump($cars);
?>

File: dataTypeEx.php
31 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Constants
 Constants are like variables except that once they are defined
they cannot be changed or undefined.
 A valid constant name starts with a letter or underscore (no $
sign before the constant name).
 Note: Unlike variables, constants are automatically global
across the entire script.
 To create a constant in PHP, use the define() function.
 Syntax
 define(name, value, case-insensitive)
 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
 Constants are automatically global and can be used across the
entire script. File: constantEx.php
32 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Operators
 Operators are used to perform operations on variables
and values.
 PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

33 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Arithmetic Operators
 PHP arithmetic operators are used with numeric values to perform common
arithmetical operations:

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
(Introduced in PHP 5.6)

34 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Assignment Operators
 PHP assignment operators are used with numeric values to write a value to a
variable.
 The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.

Assignment Same as... Description


$x = $y $x = $y The left operand gets set to the value of the
expression on the right
$x += $y $x = $x + $y Addition
$x -= $y $x = $x – $y Subtraction
$x *= $y $x = $x * $y Multiplication
$x /= $y $x = $x / $y Division
$x %= $y $x = $x % $y Modulus

35 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Comparison Operators
 PHP comparison operators are used to compare two values (number or string)
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y,
and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y,
or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or $x >= $y Returns true if $x is greater than or
equal to equal to $y
36 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
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.

Operator Name Description


++$x Pre-increment Increments $x by one, then
returns $x
$x++ Post-increment Returns $x, then
increments $x by one
--$x Pre-decrement Decrements $x by one,
then returns $x
$x-- Post-decrement Returns $x, then
decrements $x by one

37 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Logical Operators
 The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators


 PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
38 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Array Operators
 The PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of
the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

39 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP 5 if...else...elseif Statements
 if (condition) {
code to be executed if condition is true;
}
 if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
 if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
40 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
The PHP switch Statement
 switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

41 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


The PHP while Loop
 The while loop executes a block of code as long as the
specified condition is true.
 while (condition is true) {
code to be executed;
}
 <?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
42 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
The PHP do...while Loop
 The do...while loop will always execute the block of code
once, it will then check the condition, and repeat the loop
while the specified condition is true.
 do {
code to be executed;
} while (condition is true);
 <?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

43 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


The PHP for Loop
 The for loop is used when you know in advance how many
times the script should run.
 for (init counter; test counter; increment counter) {
code to be executed;
}
 Parameters:
 init counter : Initialize the loop counter value
 test counter : Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
 increment counter : Increases the loop counter value
 <?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
44 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
The PHP foreach Loop
 The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
 foreach ($array as $value) {
code to be executed;
}
 For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
 <?php
$colors
= array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
45 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Arrays
 An array stores multiple values in one single variable.
 You can access the values by referring to an index
number.
 In PHP, the array() function is used to create an array.
 $names = array("Sanjay", "Ajay", "Vijay");
 In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or
more arrays

46 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Indexed Arrays
 There are two ways to create indexed arrays:
 The index can be assigned automatically (index always
starts at 0), like this:
 $names = array("Sanjay", "Ajay", "Vijay");
 or the index can be assigned manually:
 $cars[0] = "Sanjay";
$cars[1] = "Ajay";
$cars[2] = "Vijay";
 The count() function is used to return the length (the
number of elements) of an array:
 echo count($names); //Output: 3
47 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Loop Through an Indexed Array
 <!DOCTYPE html>
<html>
<body>
<?php
$names = array("Sanjay", "Ajay", "Vijay");
$arrlength = count($names);
for($x = 0; $x < $arrlength; $x++) {
echo $names[$x];
echo "<br>";
}
?>
</body>
</html>
48 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Associative Arrays
 Associative arrays are arrays that use named keys that
you assign to them.
 There are two ways to create an associative array:
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
 or:
 $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
 The named keys can then be used in a script:
 echo "Peter is " . $age['Peter'] . " years old.";

49 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Loop Through an Associative Array
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

</body>
</html>

50 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP - Multidimensional Arrays
 A multidimensional array is an array containing one or
more arrays.
 A two-dimensional array is an array of arrays.
 For a two-dimensional array you need two indices (row
and column) to select an element.
Name Stock Sold $cars = array
(
Alto 22 18
array("Alto",22,18),
WagonR 15 13 array("WagonR",15,13),
array("Swift",5,2),
Swift 5 2
array("Ciaz",17,15)
Ciaz 17 15 );

 We can store the data from this table in a two-dimensional array, as shown above.

51 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Accessing the elements from :
Two Dimensional Array
 <!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Alto",22,18),
array("WagonR",15,13),
array("Swift",5,2),
array("Ciaz",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
 Output:
 Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

52 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Accessing the elements from Two Dimensional Array:
We can also put a For loop inside another For loop to get the elements
of the $cars array (we still have to point to the two indices):
 <!DOCTYPE html>  Output:
<html>
<body>
<?php
$cars = array
(
array("Alto",22,18),
array("WagonR",15,13),
array("Swift",5,2),
array("Ciaz",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>

53 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Sort Functions For Arrays
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according
to the value
 ksort() - sort associative arrays in ascending order, according
to the key
 arsort() - sort associative arrays in descending order,
according to the value
 krsort() - sort associative arrays in descending order,
according to the key
 <?php
$cars = array("Alto", "WagonR", "Swift");
sort($cars);
?>
54 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Working with Strings and Functions
 A string is a sequence of characters, like "Hello world!".
 Some commonly used functions to manipulate strings are:
 strlen() : returns the length of a string.
 echo strlen("Hello world!"); // outputs 12
 str_word_count() : counts the number of words in a string
 echo str_word_count("Hello world!"); // outputs 2
 strrev() : reverses a string
 echo strrev("Hello world!"); // outputs !dlrow olleH
 strpos() : searches for a specific text within a string.
 If a match is found, the function returns the character position of the first match. If
no match is found, it will return FALSE.
 The first character position in a string is 0 (not 1).
 echo strpos("Hello world!", "world"); // outputs 6
 str_replace() : replaces some characters with some other characters in a string.
 The example below replaces the text "world" with "Sanjay":
 echo str_replace("world", "Sanjay", "Hello world!");
// outputs Hello Sanjay!
For More functions Refer https://www.w3schools.com/php/php_ref_string.asp
55 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP User Defined Functions
 A user defined function declaration starts with the word "function":
 Syntax:
 function functionName() {
code to be executed;
}
 Note:
 A function name can start with a letter or underscore (not a number).
 Function names are NOT case-sensitive.
 <?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>
56 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP Function Arguments
 Arguments are specified after the function name, inside
the parentheses.You can add as many arguments as you
want, just separate them with a comma.
 <?php
function greetings($name) {
echo "Hello $name<br>";
}

greetings("Sanjay");
greetings("Students");
?>

57 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


A function with two arguments
 <!DOCTYPE html>
<html>
<body>

<?php
function joinYear($name, $year) {
echo "$name join in $year <br>";
}

joinYear("Sanjay","2002");
joinYear("Ajay","2010");
?>

</body>
</html>
58 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
A function with default argument value
 If we call the function without arguments it takes the
default value as argument (if specified).
 <?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight();//will use the default value of 50


setHeight(135);
?>

59 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Functions - Returning values
 To let a function return a value, use the return statement:
 <!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
60 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Include and Require Statements
 The include (or require) statement takes all the text/
code/ markup that exists in the specified file and copies it
into the file that uses the include statement.
 Including files is very useful when you want to include the
same PHP, HTML, or text on multiple pages of a website.
 Including files saves a lot of work. This means that you can
create a standard header, footer, or menu file for all your
web pages. Then, when the header needs to be updated,
you can only update the header include file.
 Syntax
 include 'filename';
or
require 'filename';
61 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Include vs. Require
 The include and require statements are identical,
except upon failure:
 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 (Comfort).
 Otherwise, in case of complex PHP application coding,
always use the require statement. This will help avoid
compromising your application's security and integrity,
just in-case one key file is accidentally missing. (Security)
File: address.php, includeEx.php, requireEx.php
62 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Processing HTML Form Input:
 <!DOCTYPE HTML> The form data is sent with the HTTP POST method.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
 <html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html> File: Welcome_Post.html, Welcome_Post.php
63 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
Processing HTML Form Input:
 <!DOCTYPE HTML> The form data is sent with the HTTP GET method.
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
 <html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html> File: Welcome_Get.html, Welcome_Get.php
64 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
GET vs. POST
 Both GET and POST create an array (e.g. array( key => value,
key2 => value2, key3 => value3, ...)). This array holds key/value
pairs, where keys are the names of the form controls and
values are the input data from the user.
 Both GET and POST are treated as $_GET and $_POST.
These are superglobals, which means that they are always
accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.
 $_GET is an array of variables passed to the current script via
the URL parameters.
 $_POST is an array of variables passed to the current script
via the HTTP POST method.

65 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


When to use GET?
 Information sent from a form with the GET method is
visible to everyone (all variable names and values are
displayed in the URL). GET also has limits on the amount
of information to send. The limitation is about 2000
characters. However, because the variables are displayed
in the URL, it is possible to bookmark the page. This can
be useful in some cases.
 GET may be used for sending non-sensitive data.
 Note: GET should NEVER be used for sending
passwords or other sensitive information!

66 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


When to use POST?
 Information sent from a form with the POST method is
invisible to others (all names/values are embedded
within the body of the HTTP request) and has no limits
on the amount of information to send.
 However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
 Developers prefer POST for sending form data.

67 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


Dynamic Form
 http://techstream.org/Web-Development/PHP/Dynamic-
Form-Processing-with-PHP
 https://www.tutdepot.com/php-dynamic-form-elements/
 http://www.bogotobogo.com/php/php9_dynamic_content
s.php
 http://www.c-sharpcorner.com/article/create-dynamic-
invoice-form-using-php/

68 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


File Handling in PHP
 You often need to open and process a file for different
tasks. Hence, file handling is an important part of any web
application.
 PHP has several functions for creating, reading, uploading,
and editing files.
 Sample File: webdictionary.txt
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language File: webdictionary.txt
69 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.
PHP readfile() Function
 The readfile() function reads a file and writes it to the
output buffer.
 <!DOCTYPE html>
<html>
<body>
<?php
echo readfile("webdictionary.txt");
?>
</body>
</html>
File: readfileEx.php

70 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Open File - fopen()
 A better method to open files is with the fopen()
function.
 This function gives you more options than the readfile()
function.
 The first parameter of fopen() contains the name of the
file to be opened and the second parameter specifies in
which mode the file should be opened.
 Syntax:
 $myfile = fopen("webdictionary.txt", "r")

71 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new
w
file if it doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File
a
pointer starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for write only. Returns FALSE and an error if file
x
already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a
w+
new file if it doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File
a+
pointer starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for read/write. Returns FALSE and an error if file
x+
already exists

72 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Read File - fread()
 The fread() function reads from an open file.
 The first parameter of fread() contains the name of the file
to read from and the second parameter specifies the
maximum number of bytes to read.
 Syntax:
 The following PHP code reads the "webdictionary.txt" file to the end:
 fread($myfile, filesize("webdictionary.txt"));
PHP Close File - fclose()
 The fclose() function is used to close an open file.
 The fclose() requires the name of the file (or a variable that
holds the filename) we want to close.
 Syntax:
 fclose($myfile);
73 Dr. Sanjay P. Bhakkad, Associate Professor,
IMSCD&R Ahmednagar.
PHP File: Open, Read and Close
 <!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
File: fileOpenEx.php

74 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Read Single Line - fgets()
 The fgets() function is used to read a single line from a
file.
 Note: After a call to the fgets() function, the file pointer
has moved to the next line.
 <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

File: fileFgetsEx.php

75 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Check End-Of-File - feof()
 The feof() function checks if the "end-of-file" (EOF) has been
reached.
 The feof() function is useful for looping through data of
unknown length.
 The example below reads the "webdictionary.txt" file line by line,
until end-of-file is reached:
 <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?> File: fileFeofEx.php

76 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Read Single Character - fgetc()
 The fgetc() function is used to read a single character from a
file.
 Note: After a call to the fgetc() function, the file pointer
moves to the next character.
 The example below reads the "webdictionary.txt" file character by
character, until end-of-file is reached:
 <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?> File: fileFgetcEx.php

77 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Create File - fopen()
 The fopen() function is also used to create a file.
 This can be done by setting the mode paramater (2nd
parameter) as ‘w’ for writing or ‘a’ appending.
 The example below creates a new file called "testfile.txt".
The file will be created in the same directory where the
PHP code resides:
 Syntax:
 $myfile = fopen("testfile.txt", "w")

78 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Write to File - fwrite()
 The fwrite() function is used to write to a file.
 The first parameter of fwrite() contains the name of the
file to write to and the second parameter is the string to
be written.
 The example below writes a couple of names into a new
file called "testfile.txt ":
 <?php
$myfile = fopen("testfile.txt", "w") or die("Unable to open file!");
$txt = "Sanjay Bhakkad\r\n";
fwrite($myfile, $txt);
$txt = "Kush Bhakkad\r\n";
fwrite($myfile, $txt);
fclose($myfile);
?> File: fileFwriteEx.php

79 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Append to File
<?php
$myfile = fopen("testfile.txt", "a") or die("Unable to open file!");
$txt = "Pradnya Bhakkad\r\n";
fwrite($myfile, $txt);
$txt = "Girish Bhakkad\r\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

File: fileAppendEx.php

80 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.


PHP Delete a File
 The unlink() function deletes a file.
 This function returns TRUE on success, or FALSE on failure.
 <?php
$myfile = "testfile.txt";
if (!unlink($myfile))
{
echo ("Error deleting $myfile");
}
else
{
echo ("Deleted $myfile");
}
?>
File: fileDeleteEx.php

81 Dr. Sanjay P. Bhakkad, Associate Professor, IMSCD&R Ahmednagar.

Das könnte Ihnen auch gefallen