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

Intro-to-PHP

PHP, which stands for 'PHP Hypertext Preprocessor', is an open-source, server-side scripting language primarily used for generating dynamic web pages by embedding scripts within HTML. It is an interpreted language that ensures code confidentiality by executing on the server-side, and it offers compatibility with various databases, making it versatile for web application development. Key features include easy maintenance through modular design, support for multiple data types, and control structures for conditional logic and loops.

Uploaded by

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

Intro-to-PHP

PHP, which stands for 'PHP Hypertext Preprocessor', is an open-source, server-side scripting language primarily used for generating dynamic web pages by embedding scripts within HTML. It is an interpreted language that ensures code confidentiality by executing on the server-side, and it offers compatibility with various databases, making it versatile for web application development. Key features include easy maintenance through modular design, support for multiple data types, and control structures for conditional logic and loops.

Uploaded by

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

Introduction

to PHP
PRESENTED BY: ENGR. ROGER R. ABULENCIA

1
What is PHP?
PHP == ‘PHP Hypertext Preprocessor’
Open-source, server-side scripting language
Used to generate dynamic web-pages
PHP scripts reside between reserved PHP tags
◦ This allows the programmer to embed PHP scripts within HTML pages

• PHP stands for "PHP Hypertext Preprocessor" and is an open-source, server-


side scripting language.
• It is primarily used to generate dynamic web pages by embedding scripts
directly into HTML.
• The PHP tags <?php ... ?> allow PHP scripts to be integrated seamlessly with
HTML.
• Key advantages:
• Server-side execution ensures code security as PHP code is not visible
to the client.
• Various built-in functions in PHP facilitate rapid web application
development.
• Compatibility with multiple databases (e.g., MySQL) enhances its
versatility

2
What is PHP (cont’d)
 Interpreted language, scripts are parsed at run-time rather than compiled
beforehand
 Executed on the server-side
 Source-code not visible by client
 ‘View Source’ in browsers does not display the PHP code
 Various built-in functions allow for fast development
 Compatible with many popular databases

1. PHP is an interpreted language:


• What it means: PHP scripts are not precompiled into machine code. Instead, they are interpreted line-by-line at
runtime by the PHP engine.
• Implications:
• Developers can make changes to the code and see the results immediately without the need for
recompilation.
• This allows for faster development cycles, but it may be slightly slower than compiled languages like
C++ because the interpretation happens at runtime.
Example:
php code
<?php
echo "Hello, World!";
?>
When this script runs on a server, the PHP interpreter parses and executes it immediately to produce the output.

2. The server-side nature of PHP ensures source code confidentiality:


• What it means: PHP code is executed on the server, and only the resulting output (e.g., HTML, JSON) is sent to
the client's browser. The client cannot see the original PHP code.
• Implications:
• Sensitive information such as database credentials or application logic remains hidden from end users.
• This makes PHP secure for backend operations compared to client-side languages like JavaScript,
where code is visible in the browser's developer tools.

3. Compatibility with databases like MySQL:


• What it means: PHP has built-in support and extensions for interacting with databases, particularly MySQL, but
also others like PostgreSQL, SQLite, and MongoDB.
• Why it’s useful:
• PHP makes it easy to create dynamic, database-driven web applications.
• It supports powerful libraries like PDO (PHP Data Objects) or mysqli to handle database connections,
queries, and transactions securely.

3
3(+1) Tier architecture
voice
HTML

touch Browser HTTP PHP script SQL


Database
(Chrome, Edge,
FireFox,
Opera) Web Server Database
vision HTML (Apache, IIS) tables
Desktop Server
(PC or MAC)

SMS Remote
services Web Service
SMS system
Client
application

1. Presentation Tier (Front-End):


• HTML: The primary markup language used to design the web pages presented to the user.
• Browser: Web browsers like Chrome, Edge, Firefox, and Opera interpret the HTML and render it for
the user. They act as the interface for interaction with the application.
• Devices: The interface supports various types of interaction, such as:
• Voice: Using voice recognition or commands.
• Touch: Interactions via touchscreens.
• Vision: User interface visual elements are designed to be accessible for end users.
• SMS System: Represents external systems that provide interaction via text messages, often integrated
for notifications or authentication.

2. Application Tier (Middleware):


• PHP Script: The server-side logic is handled here. PHP processes requests, interacts with the database,
and dynamically generates HTML content to be sent back to the browser.
• Web Server: Software like Apache or IIS hosts the PHP script and handles HTTP requests and
responses. It bridges the client-side requests with the server-side application logic.

3. Data Tier (Back-End):


• Database Server: Stores structured data in tables and is accessed using SQL queries. This tier manages
data storage, retrieval, and integrity.
• Database: Represents the actual data storage layer, which is queried by the PHP script to serve
dynamic content to the user.

4. (+1) Additional Tier (External Services):


• Remote Services: These could include third-party APIs or web services accessed by the application. Examples include payment
gateways, external authentication services, or cloud-based resources.
• Client Application: Acts as an intermediary, making requests to remote services and integrating their
data into the application workflow.
PHP advantage
Any changes to header or footer only require editing of a single file.
This reduces the amount of work necessary for site maintenance and
redesign.
Helps separate the content and design for easier maintenance

Header

Page 1 Page 2 Page 3 Page 4 Page 5


Content Content Content Content Content

Footer

• PHP facilitates easier maintenance of web applications by separating content and


design. For example:
• Centralizing reusable components like headers or footers into single files.
• Changes in these centralized files automatically reflect across all pages.
• This modular approach improves maintainability and reduces redundancy.

5
What does PHP code look like?
 Structurally similar to C/C++
 Supports procedural and object-oriented paradigm (to some degree)
 All PHP statements end with a semi-colon
 Each PHP script must be enclosed in the reserved PHP tag

<?php

?>

6
Comments in PHP
Standard C, C++, and shell comment symbols

// C++ and Java-style comment

# Shell-style comments

/* C-style comments
These can span multiple lines */

Example:
PHP code
<?php
// Single-line comment
# Another single-line comment
/*
Multi-line comment
*/
echo "This is a PHP script!";
?>

7
Variables in PHP
 PHP variables must begin with a “$” sign
 Case-sensitive ($Foo $foo $fOo)
 Global and locally-scoped variables
 Global variables can be used anywhere
 Local variables restricted to a function or class
 Certain variable names reserved by PHP
 Form variables ($_POST, $_GET)
 Server variables ($_SERVER)
 Etc.

• Variables in PHP:
• Must start with a $ sign.
• Are case-sensitive ($Foo ≠ $foo).
• Can be global (accessible anywhere) or local (restricted to a function or class).
• Special variable types include:
• $_POST and $_GET for handling form inputs.
• $_SERVER for accessing server environment data.

8
Variable usage

<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable

$foo = ($foo * 7); // Multiplies foo by 7


$bar = ($bar * 7); // Invalid expression
?>

• PHP supports various data types, and variable manipulation depends on context:
• Numerical operations are valid on numbers.
• Invalid operations on incompatible types trigger errors.

9
Echo
 The PHP command ‘echo’ is used to output
the parameters passed to it
 The typical usage for this is to send data to the
client’s web-browser
 Syntax
 echo string arg1 [, string argn...]

• The echo command outputs text or variables to the web browser.


• It is a straightforward method for displaying data in PHP.

10
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable

echo $bar; // Outputs Hello


echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>

Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it


with 25
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as “\n”
or “\\”)

• The echo statement outputs strings and variables to the browser.


• Strings in single quotes (' ') are treated literally and are not evaluated:
• Variables and escape sequences (e.g., \n) inside single quotes are displayed as
plain text.
• Strings in double quotes (" ") are evaluated:
• Variables are replaced with their values, and escape sequences are processed.

11
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>

$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5

• PHP supports standard arithmetic operations:


• Addition (+), subtraction (-), multiplication (*), division (/), and compound
assignments like +=.
• You can perform calculations and display results directly in the output.

12
Concatenation
Use a period to join strings into one.

<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>

Hello PHP

• Strings in PHP are concatenated using a period (.).


• You can combine multiple strings into one.

13
Escaping the Character
If the string has a set of double quotation marks that must remain
visible, use the \ [backslash] before the quotation marks to ignore and
display them.

<?php
$heading=“\”Computer Science\””;
Print $heading;
?>

“Computer Science”

• Use a backslash (\) to escape special characters in strings, such as double quotes (").
• This ensures characters like quotes are displayed as part of the string.

14
PHP Control Structures
if (expr) statement

<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>

• The if statement is used to execute code based on a condition.


• It can be expanded with else and else if.

15
PHP Control Structures

if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}

• This shows how PHP handles conditional branching using if, else if, and else
statements. In PHP, these control structures allow you to execute different blocks of
code based on whether certain conditions are true or false.
• How It Works?
• When the script runs, it starts at the top condition (if ($foo == 0)) and checks
it. If $foo is zero, the code inside that block executes, and no other conditions
are checked.
• If $foo is not zero, it moves to the elseif block. If $foo is between 1 and 5, that
block executes.
• If neither of the previous conditions is true, then the else block runs,
providing a fallback message for any other value of $foo.

16
PHP Control Structures
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
default:
echo ‘Enter correct option’;

}
?>

• The switch statement simplifies multiple if-else conditions.


• It evaluates an expression and matches it against case values.

17
Loops
while (condition) {statements;}

<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>

hello PHP. hello PHP. hello PHP.

• A while loop runs as long as its condition is true.


• It is useful for repeating code with an unknown number of iterations.

18
Loops
for (expr1; expr2; expr3)
statement
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>

• A for loop is often used when the number of iterations is known beforehand.
• Syntax: for (initialization; condition; increment/decrement).

19
Loops
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo “$value \n”;
}
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value);//break the reference
?>

• The foreach loop is specifically for iterating over arrays.


• It accesses each element without needing an explicit index.

20
Loops
foreach ($arr as $key => $value) {
echo "Key:$key; Value:$value<br />\n";
}

break ends execution of the current for, foreach, while, do-while


or switch structure.
continue is used within looping structures to skip the rest of the current loop
iteration and continue execution at the condition evaluation and then the
beginning of the next iteration.

• The foreach loop iterates over elements in an array, associating a key with its
corresponding value.
• A do-while loop ensures the block of code runs at least once before the condition is
checked.

21
Arrays
An array in PHP is actually an ordered map which maps
values to keys.
An array can be thought of in many ways:

Linearly indexed array , list (vector), hash table (which is


an implementation of a map), dictionary, collection, stack
(LIFO), queue (FIFO)

• Arrays are ordered maps in PHP that associate values with keys. They can function as:
• Linear arrays (e.g., indexed arrays)
• Hash tables (key-value pairs)
• Stacks/Queues (Last In First Out, First In First Out)
• Multidimensional arrays

22
Arrays
Kinds of arrays:
◦ numeric arrays.
◦ associative arrays.
◦ multi dimensional arrays.

• Numeric Arrays: Keys are numbers.


• Associative Arrays: Keys are strings or identifiers.
• Multidimensional Arrays: Arrays within arrays.

23
Arrays
In numeric arrays each key value corresponds to numeric values.
They can be divided into two categories
1.automatic numeric array index.
2.manual array numeric index.
automatic numeric array index
<?php
$x=array(1,2,3);
print_r($x);
?>
o/p: array(0=>1,1=>2,2=>3)

• Automatic Numeric Index:


• PHP assigns indexes automatically starting from 0. Example:
• PHP code
$x = [1, 2, 3];
print_r($x); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

24
Arrays
Manual array numeric index
<?php
$x[2]=10; $x[3]=50;//$x=array(2=>10,3=>50);
echo $x[2]; echo $x[3];
?>
Associative arrays
In associated arrays each ID associated with its value
<?php
$x=array(“ab”=>1,”cd”=>2,”xy”=>3);
print_r($x);
?>

• Manual Numeric Index:


• Keys are explicitly defined. Example:
• PHP code
$x[2] = 10;
$x[3] = 50;
print_r($x); // Output: Array ( [2] => 10 [3] => 50 )

• Each key is associated with a specific value.


• Example:
• PHP code
$x = ["ab" => 1, "cd" => 2, "xy" => 3];
print_r($x); // Output: Array ( [ab] => 1 [cd] => 2 [xy] => 3 )

25
Arrays
Multidimensional Arrays-An array contains one or more arrays
<?php
$z=array(array(10,20,30),array(40,50,60));
print_r($z);

?>

Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 )
[1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) )

• These arrays contain other arrays as elements

26
Arrays
<?php
$x=array(“ab”=>1,array(2,3,4),”cd”=>8);
print_r($x);
?>

Array ( [“ab”] => 1 [0] => Array ( [0] => 2 [1] => 3 [2] => 4
) [”cd”] => 8 )

27
Arrays
<?php
$x=array(3=>4,array(2,3,4),5);
print_r($x);
?>

Array ( [3] => 4 [4] => Array ( [0] => 2 [1] => 3 [2] =>
4 ) [5] => 5 )

28
Arrays
Array operations
sort
ksort
rsort
krsort
array_merge
array_combine
array_intersect

• Common operations include:


• sort: Sort values in ascending order.
• rsort: Sort values in descending order.
• ksort: Sort by keys in ascending order.
• krsort: Sort by keys in descending order.
• array_merge: Combine multiple arrays.
• array_combine: Create an array by using one array for keys and another for
values.
• array_intersect: Find common values between arrays

29
Date Display
$datedisplay=date(“yyyy/m/d”);
print $datedisplay;

2024/12/7

$datedisplay=date(“l, F J, Y”);
print $datedisplay;

Saturday, December 12,


2024

• PHP provides the date() function to format and display dates.


• Examples:
• PHP code
echo date("Y/m/d"); // Output: 2024/12/07
echo date("l, F j, Y"); // Output: Thursday, December 7, 2024

• Format Specifiers:
• Y: Full year (e.g., 2024).
• m: Month with leading zeros (e.g., 12 for December).
• d: Day of the month with leading zeros (e.g., 07).
• Double Quotes:
• Ensure you're using standard double quotes (") instead of typographic quotes
(“”) in the date() function.

• Correct Date Format Specifiers:


• l (lowercase "L"): Full weekday name (e.g., Saturday).
• F: Full month name (e.g., December).
• j: Day of the month without leading zeros (e.g., 7).
• Y: Full numeric year (e.g., 2024).
• Standard Double Quotes:
• Use standard double quotes (") instead of typographic quotes (“ or ”).

30
Month, Day & Date Format Symbols

M Jan
F January
m 01
n 1

Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon

It describes how PHP handles date and time formatting using predefined format
symbols. These symbols allow developers to customize the output of date and time in a
readable format.

31
Functions

Functions MUST be defined before then can be called


Function headers are of the format

function functionName($arg_1, $arg_2, …, $arg_n)

Unlike variables, function names are not case sensitive

Overview: Functions are blocks of code designed to perform specific tasks. They must
be defined before being called. Unlike variables, function names are not case-sensitive.

• Key Points:
• Functions must be defined before they can be called.
• Function names are not case-sensitive.
• Arguments allow dynamic behavior within the function.

32
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}

$result_1 = foo(12, 3); // Store the


function
echo $result_1; // Outputs 36
echo foo(12, 3); // Outputs 36
?>

• Function Definition: foo is a reusable function that accepts arguments and performs
operations.
• Parameters and Arguments: $arg_1 and $arg_2 demonstrate how data is passed into
the function.
• Return Value: return allows the function to send back a value to the caller.
• Reuse of Code: The function is called twice with the same arguments, showcasing
how functions avoid redundancy.

33
Include Files
include “header.php”;
include (“footer.php”);

This inserts files; the code in files will be inserted into current code.
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it
will halt the script whereas include only emits a warning
(E_WARNING) which allows the script to continue.

• The include statement imports external files into the script. If the file is missing, it
emits a warning but continues execution.
• require works similarly but stops execution with a fatal error if the file is missing.

34
Include Files
The include_once statement includes and evaluates the
specified file during the execution of the script.
This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again.
The require_once statement is identical to require except
PHP will check if the file has already been included, and if so, not
include (require) it again

• include_once and require_once ensure files are included only once during execution.

35
Thank you!

36

You might also like