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

PHP_ PHP Hypertext Preprocessor

Uploaded by

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

PHP_ PHP Hypertext Preprocessor

Uploaded by

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

PHP: Hypertext

Preprocessor

CSCI 165
Introduction

Initially released in 1995

Developed by Rasmus Lerdorf

PHP stands for - PHP: Hypertext Preprocessor

Open source

Server side scripting language

Used in Web Development


Reasons for PHP’s popularity

(1) Easy to Learn

(2) Cross-platform compatibility

(3) Fast performance

(4) Large community of developers


Integrating PHP into a HTML doc

Use delimiters to mark the beginning and end of a code block

More info: https://www.w3schools.com/php/php_syntax.asp


Outputting content to screen

Can use two “functions”: print or echo

<
Data Types

Data Type Example Description

String $name = “John”; Used for text data

Integer $age = 25; Whole numbers

Float $price = 9.99; Decimal numbers

Boolean $turned_on = true; True or false values

Array $fruits = array (apple, orange, lemon); Used to store multiple values

More information: https://www.w3schools.com/php/php_datatypes.asp


PHP Operators

Arithmetic

Comparison

Logical

More info: https://www.w3schools.com/php/php_operators.asp


Variables

● Variables are used to store data that can be reused in a script

● PHP Variables start with a $ followed by a name

● Can only contain letters, numbers and underscores

● Cannot start with a number

● Case - sensitive $myName and $myname are not the same


Assigning values to variables (1)

To initialize (assign a value) to a variable, a value can be “hard-coded” in (uncommon because


variables should be used for temporary storage of values):

More info: https://www.w3schools.com/php/php_variables.asp


Assigning values to variables (2)

A value could be assigned via the results of a calculation e.g.:


Assigning values to variables (3)

Values can also be requested from the user of the program, using the readline function:

When this line is executed, the terminal side will show the string statement and the user will be
able to type in a value:
Arrays Overview

● An array is a special type of variable

● It is an ordered collection of data

● It holds multiple values, typically of a similar type

● Arrays usually hold similar data


Types of Array

Indexed array - each element has a numeric index

Associative array - each element has a string index

Multidimensional array - an array of arrays


Initializing an Indexed array
Initializing an Associative array
Accessing an Indexed array
Accessing an Associative array

(replace numeric key with

string key)
Adding to an array
Deleting from an array

Use the unset function, providing the


argument of the array name and the key value:

The code above removes “Volvo” which is at position 0


Sorting Arrays

1. sort()Sorts an array by values in ascending order. Re-indexes the array, meaning the original keys are lost.

Example: sort($array);

2. rsort()Sorts an array by values in descending order. Re-indexes the array, so keys are lost.

Example: rsort($array);

3. asort()Sorts an array by values in ascending order while preserving the original keys.

Example: asort($array);

4. arsort()Sorts an array by values in descending order while preserving the original keys.

Example: arsort($array);
Outputting an array (print_r function)
Looping through an indexed array
Looping through an Associative array
Counting elements in an array
Use Count() function

For more information https://www.w3schools.com/php/php_arrays.asp


Functions

A function is a block of code that performs a specific task

It can be reused throughout the script

A function is defined using the function keyword followed by a


function name, a set of parentheses() and curly braces{}
containing the function code

Functions can be user-defined or built-in


Functions (2) - User Defined
Functions (3) - Built in

String functions
PHP Manual - all
Array functions Built-in Functions

Math functions

Date & Time functions

File System functions


Functions (4) - Built in

To use a built-in function;

(1) Call the function by name


(2) Provide any necessary arguments

More info: https://www.w3schools.com/php/php_functions.asp


Control Structures

A control structure is a block of programming that


analyzes variables and chooses a direction in
which to go based on given parameters.

The 3 basic types of control structure are:


● Sequential
● Selection
● Iteration
Control Structures
Sequential

The default control structure

Example:
§Input number between 1 and 10;
§Input second number between 11 and 20;
§Add first number to second number;

Statements are executed line by line,


in the order that they appear
Selection

Selection is used to test a condition

Then a sequence of statements is executed


based on whether the condition is true or false

The program has to choose between


2 or more alternative paths
Repetition/Iteration

Repeatedly executes a series of


Statements as long as a condition
is true

The condition may be pre-defined


or open-ended
Selection Types

https://www.w3sch
ools.com/php/php_if
_else.asp
Selection Examples - If statement
Selection Examples - If Else statement
Selection Examples - If Elseif Else statement

More info: https://www.w3schools.com/php/php_if_else.asp


Selection Examples - Switch statement

More info:
https://www.w3sch
ools.com/php/php_s
witch.asp
Iteration Types
For Loop (counter-controlled loop) - executes a block of code a fixed
number of times

For each Loop (counter-controlled loop) - used to iterate through an array


and execute a block of code for each element

While Loop (condition-controlled loop) - executes a block of code while a


condition is true - condition is specified at the beginning of the loop

Do While Loop (condition-controlled loop) - executes a block of code


while a condition is true - condition is specified at the end of the loop
meaning code always executed at least once
Iteration examples- For Loop
The For Loop consists of
3 statements:
(1) Initialization statement
(evaluated once initially)

(2) Condition statement


(evaluated before each
iteration - code block only
executed if true)

(3) Increment statement


(evaluated AFTER each
increment, increases value
of variable (e.g.
$Student_number by 1)
Iteration examples- For Each Loop to
access values
Syntax

Code
example

Output
Iteration examples- For Each Loop to
access values AND keys
Syntax

Code
example

Output
Iteration examples- While Loop
Iteration examples- Do While Loop

More info: https://www.w3schools.com/php/php_looping.asp


Website Form uses

User registration
Login
Contact form
Newsletter subscription
Order form
etc….
HTML Form Tags

<form></form> - create the form


HTML Tags:
<fieldset></fieldset> - groups related elements in a form
https://www <legend></legend> - gives a caption to the fieldset
.w3schools.c
om/tags/tag <label></label> - defines a label for an input element
_form.asp <input> - void tag - specifies a field where user can enter
data
HTML Form Tags and attributes

<form></form> - create the form


HTML Tags:
<fieldset></fieldset> - groups related elements in a form
https://www <legend></legend> - gives a caption to the fieldset
.w3schools.c
om/tags/tag <label></label> - defines a label for an input elemnt
_form.asp <input> - void tag - specifies a field where user can enter
data
HTML form input types

Text Checkbox
HTML input
types: Email Submit

https://www Password Reset


.w3schools.c
Number Search
om/html/ht
ml_form_inp Radio Date
ut_types.asp
HTML form attributes

<form action =”handleform.php” method=”post”>


Attributes in
red are <input type=”text” name=”suitablename”
required id=”suitablename” required>

Attributes in <input type=”submit” value=”Send”>


bold are <label for=”typename”>
optional
PHP - HTML Form Code Example
PHP - Handling Form Data

When a user submits a form, the data is sent to the


https://www.w3s
server as an HTTP request
chools.com/php/
php_forms.asp
PHP code can retrieve the form data using the
$_POST or $_GET superglobal array
These arrays contain key-value pairs where the keys
correspond to the name attributes of the form input
fields
PHP - handle form script
PHP - Sending Data via GET method

● Sends data as part of the URL in the HTTP request


● The data is visible in the URL address bar of the browser
● Can be bookmarked and shared with others
● Suitable for retrieving data from the server
● Has a limit on the amount of data that can be sent
(maximum length of the URL)
PHP - Sending Data via POST method

● Sends data as part of the HTTP request body


● The data is not visible in the URL address bar of the
browser
● Cannot be bookmarked or shared with others
● Suitable for submitting data to the server
● Has no limit on the amount of data that can be sent
PHP - Handling Form Data - Validation and
Verification

Validation ensures data meets specific rules BEFORE


the form is submitted. Takes place on client side.
● e.g. setting a min value on a Quantity field
Verification confirms that data submitted is
accurate/correct. This happens on the server side
AFTER the form is submitted
● E,g, server checks password matches with stored
password for an account login
PHP - Handling Form Data - Validation

In HTML, Form data can be validated (use of


required attribute and choosing suitable format for
input types)
Error messages are generated before submission if
validation fails
PHP Form Validation: Input can also be validated on the server side using
https://www.w3schoo PHP functions (e.g. empty() - checks if a variable is
ls.com/php/php_form_
validation.asp empty or not)
PHP - Handling data using mail()

● The mail() function takes several parameters, including:


○ recipient's email address
○ the subject of the email
Mail function:
https://www.w ○ the body of the email
3schools.com/p
hp/func_mail_m ○ optional headers
ail.asp
File Handling

PHP has built-in functions that can read, write and


manipulate files on a server

Can be used to store & retrieve user’s data (e.g. login


credentials)

Can write Log files that record errors - useful for


trouble-shooting
File Editing - Functions

fopen()
● Opens a file
● 2 parameters needed (file name, and mode (e.g. r, w a)

fread()
● Reads a specified number of bytes
● File must be opened before using fread()

fclose()
● Closes the file
● Necessary so that the file doesn’t continue to use system
resources
File Editing - Reading Binary files with fread()
File Editing - Reading with fgets()
If working with text file, fgets() is more appropriate to use than
fread()

fgets() reads a single line of text from a text file:


File Editing - Reading: Using a loop with fgets()

https://www.w3sc
hools.com/php/ph
p_file_open.asp
File Editing - Writing to a File
File Editing - Appending to a File
https://www.w3
schools.com/ph
p/php_file_creat
e.asp

You might also like