[go: up one dir, main page]

0% found this document useful (0 votes)
94 views61 pages

Unit-4

The document discusses PHP, a server-side scripting language that can be used to create dynamic web pages, and covers what PHP is, how to write PHP scripts, PHP variables and data types, operators, decision making and loops, arrays, and functions. It also provides examples of PHP code for various concepts like operators, conditional statements, looping, arrays, and functions.

Uploaded by

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

Unit-4

The document discusses PHP, a server-side scripting language that can be used to create dynamic web pages, and covers what PHP is, how to write PHP scripts, PHP variables and data types, operators, decision making and loops, arrays, and functions. It also provides examples of PHP code for various concepts like operators, conditional statements, looping, arrays, and functions.

Uploaded by

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

WEB DEVLOPMENT(3151606)

UNIT-4:PHP
PREPARED BY: PROF. MAYUR PRAJAPATI
What is PHP ?

 PHP stands for PHP: Hypertext Preprocessor

 PHP is a server-side scripting language

 PHP scripts are executed on the server

 PHP supports many databases (MySQL, Oracle, SQL, Generic ODBC,

etc.)

 PHP is an open source software

 PHP is free to download and use


What is a PHP File ?

 PHP files can contain text, HTML tags and scripts

 PHP files are returned to the browser as plain HTML

 PHP files have a file extension of ".php", ".php3", or ".phtml"


What is MySQL ?

 MySQL is a Database Server

 MySQL is ideal for both small and large applications

 MySQL supports standard SQL

 MySQL compiles on a number of platforms

 MySQL is free to download and use


Why PHP ?

 PHP runs on different platforms (Windows, Linux, Unix, etc.)

 PHP is compatible with almost all servers used today (Apache, IIS, etc.)

 PHP is FREE to download from the official PHP resource: www.php.net

(Version 7.4.3)

 PHP is easy to learn and runs efficiently on the server side.


PHP advantages

 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


Install LAMP

 LAMP Server is a collection of open source software used to create a web


server.
 The collection consists of:

1. Linux – the operating system

2. Apache server – the server

3. MySQL – the database system

4. PHP – the programming language


Install LAMP

 First refresh your package index...

sudo apt-get update

 ... and then install the LAMP stack:

sudo apt-get install lamp-server^

 create file through command prompt using gedit.

 save your php file in .var/www/html.

 sudo chmod -R 777 /var/www


WAMP

 WAMP Server is a software stack for Microsoft windows created by Romain


Bourdon.

1. Windows – the operating system

2. Apache server – the server

3. MySQL – the database system

4. PHP – the programming language


How to write simple PHP script ?

 PHP code must embedded with <? php ?> tag.


 Using print and echo statement the O/P can be displayed on the screen.
 Example : hello.php

Output
Comments in PHP

 Single line comment specified by //or #.

 Multiline comment specified by /* and */.

Example:
<?php
// This is a single-line comment
# This is also a single-line comment
/* This is a multiple-lines
comment block
*/
?>
Case sensitivity in PHP

 PHP Statement must be terminated by semicolon (;).

 In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions,

and user-defined functions are NOT case-sensitive.

 All variable names are case-sensitive.


Some Reserved Words For PHP
 All these are special words, associated with some meaning.

foreach continue function or break


false do global require true
extends else list return var
and elseif not this default
new for include switch static
while virtual xor
Variables in PHP

 PHP is dynamically typed language. i.e. PHP has no type declaration.

 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)
Variables in PHP
 The value can be assigned to variable by

 $variable_name=value;

 If value is not assigned to variable then by default the value is NULL.

 These variables are called unbound variables, if they are used in

expression then NULL value is automatically converted to 0.


Data Types in PHP

 Integers
 Doubles
 Booleans
 NULL − is a special type that only has one value: NULL.
 Strings
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to
PHP (such as database connections).
datatype.php

output
Operators
 Arithmetic : (+,-,/,*,%).
 Relational : (<,>,<=,>=,==)..
 Logical : ( != ,&&,||).
 Assignment : ( =).
 Increment : ( ++ ).
 Decrement : (--).

operator.php
output
Various String Operations

output
2nd Example

2) Concatenating the two string:

Ans : <? Php

$str1 = “Hello”;

$str2 = “Friends”;

print $str1 “ “ $str2 ;

?>

 O/P : Hello Friends.


3rd Example

3) Comparing Two string:


Ans : <? Php
$str1 = “Hello”;
$str2 = “Friends”;
if($strcmp($str1,$str2)==0)
print “Both r equal”;
else
print “Both r not equal”;
?>
 O/P : Both r not equal.
4th Example

4) Reverse string:

Ans : <? Php

$str1 = “Hello”;

$str2 = “Friends”;

print $strrev($str1); ?>

 O/P : olleH.
Decision Making

 If..else..

 If.elseif..else

 switch
Cont..

 It supports if-else, while statement and for loops.

1) if-else statement will be-

If ($a>$b)

$msg= “a is greater”;

else

$msg = “b is greater”;
Conditional Statements

 if statement - executes some code if one condition is true

 if...else statement - executes some code if a condition is true and another

code if that condition is false

 if...elseif....else statement - executes different codes for more than two

conditions

 switch statement - selects one of many blocks of code to be executed


Conditional Statements Example
ifelse.php
output
Conditional Statements Example
switch.php
output
Looping

 while - loops through a block of code as long as the specified condition

is true

 do...while - loops through a block of code once, and then repeats the loop

as long as the specified condition is true

 for - loops through a block of code a specified number of times

 foreach - loops through a block of code for each element in an array


Looping Statements Example
while.php
output
Looping Statements Example

dowhile.php
output
Looping Statements Example
forfibo.php
output
Looping Statements Example
forpattern.php
output
Looping Statements Example

foreach.php
output
Arrays
 It is collection of similar type of elements.

 PHP Array Types

1. Indexed Array

2. Associative Array

3. Multidimensional Array
Arrays
PHP Indexed Array
 PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an
index number by default.
 There are two ways to define indexed array:
st
 1 way: $season=array("summer","winter","spring","autumn");
 2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Arrays
PHP Associative Array

 PHP allows you to associate name/label with each array elements in PHP using
=> symbol.
 Ex:
$salary=array("A"=>"1","B"=>"2","C"=>"3");

Assoindexarray.php

output
Arrays
PHP Multidimensional Array

<?php 1 A 4000
$emp = array 2 B 5000
(
array(1,"A",4000), 3 C 3000
array(2,"B",5000),
array(3,"C",3000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
} ?>
Functions

 Function can be placed anywhere inside the PHP script.

 And it executed only after a call to it.

 Syntax of function is

function function_name()

Function body

}
 Three types of functions :

1. Functions having no parameter and no return value.


Ex: <? Php
function sum()
{
$a = 10;
$b = 20;
$c = $a + $b;
print $c;
}
print “The sum is”;
sum();
?>
2. Functions having parameters passed to it but no return value.
Ex: <? Php
function sum ($a, $b)
{
$c = $a + $b;
print $c;
}
print “The sum is”;
$x=10;
$y=20;
sum ($x, $y);
?>
3. Functions having parameters passed to it and return some value.
Ex: <? Php
function sum ($a, $b)
{
$c = $a + $b;
return $c;
}
print “The sum is”;
$x=10;
$y=20;
$z=sum ($x, $y);
print $z;
?>
Function.php

Output
Forms
 Form gives GUI the user.
 The value of the form elements can be obtained by the PHP script using
$_GET and $_POST variables.
 If we collect the values using GET method then $_GET variable is used in
the PHP script.
 Note: if the GET method is used then all variable names and values will be
displayed in the URL as a Query String.
 But if we use POST method then these values will not be displayed in the
URL.
 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.
Form Example
Phpform.html

output

Welcome.php

Welcome_get.php
Get Vs. Post
 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!
Get Vs. Post
 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.
 Moreover POST supports advanced functionality such as support for
multi-part binary input while uploading files to server.
 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.


Form Validation
<html>
<body>
<?php
// define variables and set to empty values
$nameErr = $genderErr = "";
$name = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Form Validation
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
/*$_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page. This way, the user will get error messages on the same page as
the form.*/
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $gender;
?></body></html>
Form Example
 Create HTML form to enter number. Write PHP code to display message if
number is even or odd.
phpform_odd.html
output

Getdata.php
PHP file
 PHP File System allows us to create file, read file line by line, read file
character by character, write file, append file, delete file and close file.

 The PHP fopen() function is used to open a file.

 The PHP fclose() function is used to close an open file pointer.

 The PHP fread() function is used to read the content of the file. It accepts two
arguments: resource and file size.

 The PHP fwrite() function is used to write content of the string into ffile.

 The PHP unlink() function is used to delete file.


PHP file contents reading example

file1.php

myfile.txt output
PHP Writing to File example

file2.php

output
EXCEPTION HANDLING:
PHP 5 has an exception model similar to that of other programming languages.
Exceptions are important and provides a better control over error handling.

Lets explain there new keyword related to exceptions.

1. Try − A function using an exception should be in a "try" block. If the


exception does not trigger, the code will continue as normal. However if the
exception triggers, an exception is "thrown".

2. Throw − This is how you trigger an exception. Each "throw" must have at
least one "catch".

3. Catch − A "catch" block retrieves an exception and creates an object


containing the exception information.
CONT..
When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block. If an
exception is not caught, a PHP Fatal Error will be issued with an "Uncaught
Exception ...

1. An exception can be thrown, and caught ("catched") within PHP. Code may
be surrounded in a try block.

2. Each try must have at least one corresponding catch block. Multiple catch
blocks can be used to catch different classes of exceptions.

3. Exceptions can be thrown (or re-thrown) within a catch block.


Example
Following is the piece of code, copy and paste this code into a file and verify the
result.

<?php
try {
$error = 'Always throw this error';
throw new Exception($error);

// Code following an exception is not executed.


echo 'Never executed';
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>
In the above example $e->getMessage function is used to get error message.

There are following functions which can be used from Exception class.

1. getMessage() − message of exception

2. getCode() − code of exception

3. getFile() − source filename

4. getLine() − source line

5. getTrace() − n array of the backtrace()

6. getTraceAsString() − formated string of trace


OOP with PHP

 Encapsulation

 Message passing

 Inheritance

 Polymorphism
Example using class and object
oop.ph
output p

output
Example using constructor and destructor

condes.ph
p
output
THANK YOU……

You might also like