0% found this document useful (0 votes)
5 views27 pages

PHPnotes

The document outlines the differences between server-side and client-side scripting, highlighting that server-side scripting operates on the web server and is not visible to clients, while client-side scripting runs in the user's browser and is visible. It also introduces PHP as a server-side scripting language, detailing its capabilities, advantages, and installation process using XAMPP. Additionally, the document covers PHP syntax, variable definition, and control structures like if statements.

Uploaded by

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

PHPnotes

The document outlines the differences between server-side and client-side scripting, highlighting that server-side scripting operates on the web server and is not visible to clients, while client-side scripting runs in the user's browser and is visible. It also introduces PHP as a server-side scripting language, detailing its capabilities, advantages, and installation process using XAMPP. Additionally, the document covers PHP syntax, variable definition, and control structures like if statements.

Uploaded by

naidu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

the difference between server-side scripting and client-side scripting.

Server-side Scripting
 It helps work with the back end.
 It doesn’t depend on the client.
 It runs on the web server.
 It helps provide a response to every request that comes in from the user/client.
 This is not visible to the client side of the application.
 It requires the interaction with the server for the data to be process.
 Server side scripting requires languages such as PHP, [Link], ColdFusion,
Python, Ruby on Rails.
 It is considered to be a secure way of working with applications.
 It can be used to customize web pages.
 It can also be used to provide dynamic websites.

Client-side Scripting
 It helps work with the front end.
 It is visible to the users.
 The scripts are run on the client browser.
 It runs on the user/client’s computer.
 It depends on the browser’s version.
 It doesn’t interact with the server to process data.
 Client side scripting involves languages such as HTML, CSS, JavaScript.
 It helps reduce the load on the server.
 It is considered to be less secure in comparison to client side scripting.

Introduction to PHP
PHP is a server-side and general-purpose scripting language that is
especially suited for web development.

PHP originally stood for Personal Home Page. However, now, it stands
for Hypertext Preprocessor. It’s a recursive acronym because the first
word itself is also an acronym.

PHP was created by Rasmus Lerdorf in 1994. It’s currently maintained by


the PHP Development Team.
PHP is a server-side language

When you open a website on your web browser, for example,


[Link]

The web browser sends an HTTP request to a web server where


[Link] locates. The web server receives the request and responds
with an HTML document.

In this example, the web browser is a client while the web server is the
server. The client requests for a page, and the server serves the request.

PHP runs on the web server, processes the request, and returns the HTML
document.

PHP is a general-purpose language

When it comes to the purpose of the programming languages, there are


two main types: domain-specific and general-purpose languages.

The domain-specific languages are used within specific application


domains. For example, SQL is a domain-specific language. It’s used mainly
for querying data from relational databases. And SQL cannot be used for
other purposes.

On the other hand, PHP is a general-purpose language because PHP can


develop various applications.

PHP is a cross-platform language

PHP can run on all major operating systems, including Linux, Windows,
and macOS.

You can use PHP with all leading web servers such as Nginx, OpenBSD,
and Apache. Some cloud environments also support PHP like Microsoft
Azure and Amazon AWS.

PHP is quite flexible. It’s not just limited to processing HTML. PHP has
built-in support for generating PDF, GIF, JPEG, and PNG images.

One notable feature of PHP is that it supports many databases, including


MySQL, PostgreSQL, MS SQL, db2, Oracle Database, and MongoDB.

What can PHP do


PHP has two main applications:
 Server-side scripting – PHP is well-suited for developing dynamic
websites and web applications.
 Command-line scripting – like Python and Perl, you can run PHP
script from the command line to perform administrative tasks like
sending emails and generating PDF files.

The tutorials on this website mainly focus on server-side scripting.

How PHP Works


The following illustrates how PHP works:

How PHP works:

 First, the web browser sends an HTTP request to the web server,
e.g., [Link].
 Second, the PHP preprocessor that locates on the web server
processes PHP code to generate the HTML document.
 Third, the web server sends the HTML document back to the web
browser.

Advantages of PHP
Since PHP is designed for the web in the first place, it brings many
advantages to web development:

 Simple – PHP is quite easy to learn and get started.


 Fast – PHP websites typically run very fast.
 Stable – PHP is stable since it has been in existence for a long time.
 Open-source and free – PHP is open source and free. It means that
you don’t have to pay a license fee to use PHP to develop software
products.
 Community support – PHP has an active online community that
helps you whenever you face an issue.

Installing PHP on your computer allows you to safely develop and test a web application without
affecting the live system.

To work with PHP locally, you need to have the following software:

PHP
A web server that supports PHP. We’ll use the Apache webserver.
A database server. We’ll use the MySQL database server.
Typically, you won’t install all this software separately because connecting them is tricky and not
intended for beginners.

Therefore, it’s easier to find an all-in-one software package that includes PHP, a web server, and a
database server. One of the most popular PHP development environments is XAMPP.

XAMPP is an easy install Apache distribution that contains PHP, MariaDB, and Apache webserver.
XAMPP supports Windows, Linux, and macOS.

Note that MariaDB is a fork of the most popular relational database management system, MySQL.

Download XAMPP
To install XAMPP on windows, you can go to the XAMPP official website and download the suitable
version for your platform.

Install XAMPP on Windows


To install XAMPP on Windows, you can follow these steps:

Step 1. Start the installation


Double-click the downloaded file to start setting up XAMPP:

Step 2. Select components to install


Select the components that you want to install. In this step, you can select Apache, MySQL, PHP, and
phpMyAdmin, deselect other components like the following, and click the Next button to go to the
next step.

Step 3. Specifying the installation folder


Select a folder to install XAMPP. It’s recommended to install XAMPP in the c:\xampp folder. Click the
Next button to go to the next step.

Step 4. Selecting a language


Select a language for XAMPP Control Panel. By default, it’s English. And you can select your
preferred language and click the Next button to go to the next step.

Step 5. Bitnami for XAMPP


Feel free to skip this step because you don’t need Bitnami for learning PHP. Just click the Next button
to go to the next step.
Step 6. Begin installing XAMPP
And you’re now ready to install XAMPP. Click the Next button to start the installation. It’ll take a few
minutes to complete.

Step 7. Completing the XAMPP setup


Once completed, the XAMPP setup wizard shows the following screen. You can click the Finish
button to launch the XAMPP Control Panel:

Step 8. Completing the XAMPP setup


The XAMPP Control Panel lists installed services. To start a service, you click the corresponding Start
button:

The following shows the Apache web server and MySQL are up and running. The Apache web server
listens on the ports 80 and 443 while the MySQL listens on port 3306:

Step 9. Launch the XAMPP


Open the web browser and navigate to the following URL: [Link] If the installation is
completed successfully, you’ll see the welcome screen of the XAMPP.
Troubleshooting
By default, Apache uses port 80. However, if port 80 is used by another service, you’ll get an error
like this:
Problem detected!
Port 80 in use by "Unable to open process" with PID 4!
Apache WILL NOT start without the configured ports free!
You need to uninstall/disable/reconfigure the blocking application
or reconfigure Apache and the Control Panel to listen on a different port
Code language: plaintext (plaintext)
In this case, you need to change the port from 80 to a free one, e.g., 8080. To do that, you follow
these steps:

First, click the Config button that aligns with the Apache module:

Second, find the line that has the text Listen 80 and change the port from 80 to 8080 like this:

Third, click the Start button to start the Apache service. If the port is free, Apache should start
properly, as shown in the following picture:

PHP Hello World on the web browser


First, open the folder htdocs under the xampp folder. Typically, it locates
at C:\xampp\htdocs.

Second, create a new folder called helloworld.

Third, create a new file called [Link] under the helloworld folder and place
the following code in the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP - Hello, World!</title>
</head>
<body>
<h1><?php echo 'Hello, World!'; ?></h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP - Hello, World!</title>
</head>
<body>
<h1><?php echo 'Hello, World!'; ?></h1>
</body>
</html>

PHP Syntax
As a programming language, PHP has a set of rules that governs how you
write programs.

PHP code
Like HTML, you need to have the opening tag to start PHP code:
Statements
A PHP script typically consists of one or more statements. A statement is a
code that does something, e.g., assigning a value to a variable and calling
a function.

A statement always ends with a semicolon (;). The following shows a


statement that assigns a literal string to the $message variable:

$message = "Hello";
The above example is a simple statement. PHP also has a compound statement that
consists of one or more simple statements. A compound statement uses curly braces to
mark a block of code. For example:
if( $is_new_user ) {
send_welcome_email();
}

You don’t need to place the semicolon after the curly brace ( }).

The closing tag of a PHP block (?>) automatically implies a semicolon (;).
Therefore, you don’t need to place a semicolon in the last statement in a
PHP block. For example:

<?php echo $name ?>


In this example, the statement echo $name doesn’t need a semicolon.
However, using a semicolon for the last statement in a block should work
fine. For example:

<?php echo $name; ?>

Note that it’s OK if the code may not make any sense to you now because
you’ll learn more about them in the upcoming tutorial.

Whitespace & line breaks


In most cases, whitespace and line breaks don’t have special meaning in
PHP. Therefore, you can place a statement in one line or span it across
multiple lines.

For example, the following code snippets are equivalent:

login( $username, $password );

And:

login(
$username,
$password
);

Summary
 PHP is partially case-sensitive.
 PHP constructs, function names, class names are case-insensitive,
whereas variables are case-sensitive.
 A statement ends with a semicolon (;).
 Whitespace and line breaks don’t matter in PHP; do leverage them to
make the code more readable.

Define a variable
A variable stores a value of any type, e.g., a string, a number, an array, or
an object.

A variable has a name and is associated with a value. To define a variable,


you use the following syntax:

$variable_name = value;Code language: PHP (php)

When defining a variable, you need to follow these rules:

 The variable name must start with the dollar sign ( $).
 The first character after the dollar sign ( $) must be a letter (a-z) or the
underscore ( _ ).
 The remaining characters can be underscores, letters, or numbers.

PHP variables are case-sensitive. It means


that $message and $Message variables are entirely different.

The following example defines a variable called $title:

<?php
$title = "PHP is awesome!";Code language: HTML, XML (xml)

To display the values of variables on a webpage, you’ll use


the echo construct. For example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>PHP Variables</title>
</head>
<body>
<?php
$title = 'PHP is awesome!';
?>
<h1><?php echo $title; ?></h1>
</body>
</html>Code language: HTML, XML (xml)

If you open the page, you’ll see the following message:

PHP is awesome!

Another shorter way to show the value of a variable on a page is to use


the following syntax:

<?= $variable_name ?>Code language: HTML, XML (xml)

For example, the following shows the value of the $title variable in the
heading:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>PHP Variables</title>
</head>
<body>
<?php
$title = 'PHP is awesome!';
?>

<h1><?= $title; ?></h1>


</body>
</html>

Mixing PHP code with HTML will make the code unmaintainable, especially
when the application grows. To avoid this, you can separate the code into
separate files. For example:

 [Link] – store the logic for defining and assigning value to variables.
 [Link] – store the code that displays the variables.
 Use the require construct to include the code from the [Link] in
the [Link] file.

The following shows the contents of the [Link] file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>PHP Variables</title>
</head>
<body>
<h1><?= $title ?></h1>
</body>
</html>

And the following shows the contents of the [Link] file:

<?php

$title = 'PHP is awesome!';


require '[Link]';

If you open the [Link] file on the web browser, you’ll see the same
output.

By doing this, you separate the code responsible for logic and the code
responsible for displaying the file. This is called the separation of
concerns (SoC) in programming.

Summary
 A variable stores a value, and its name always starts with $ sign.
 Use the separation of concerns principle to separate the PHP logic from
HTML.

Decision and looping Statements

Introduction to the PHP if statement


The if statement allows you to execute a statement if an expression
evaluates to true. The following shows the syntax of the if statement:

<?php

if ( expression )
statement;

In this syntax, PHP evaluates the expression first. If the expression evaluates
to true, PHP executes the statement. In case the expression evaluates
to false, PHP ignores the statement.

The following flowchart illustrates how the if statement works:

The following example uses the if statement to display a message if


the $is_admin variable sets to true:

<?php

$is_admin = true;
if ($is_admin)
echo 'Welcome, admin!';Code language: HTML, XML (xml)

Since $is_admin is true, the script outputs the following message:

Welcome, admin!

Curly braces
If you want to execute multiple statements in the if block, you can use
curly braces to group multiple statements like this:

<?php

if ( expression ) {
statement1;
statement2;
// more statement
}

The following example uses the if statement that executes multiple


statements:

<?php

$can_edit = false;
$is_admin = true;

if ( $is_admin ) {
echo 'Welcome, admin!';
$can_edit = true;
}

In this example, the if statement displays a message and sets


the $can_edit variable to true if the $is_admin variable is true.

It’s a good practice to always use curly braces with the if statement even
though it has a single statement to execute like this:

<?php

if ( expression ) {
statement;
}

In addition, you can use spaces between the expression and curly braces
to make the code more readable.
Nesting if statements
It’s possible to nest an if statement inside another if statement as follows:

<?php

if ( expression1 ) {
// do something
if( expression2 ) {
// do other things
}
}
The following example shows how to nest an if statement in another if statement:
<?php

$is_admin = true;
$can_approve = true;

if ($is_admin) {
echo 'Welcome, admin!';
if ($can_approve) {
echo 'Please approve the pending items';
}
}

Embed if statement in HTML


To embed an if statement in an HTML document, you can use the above
syntax. However, PHP provides a better syntax that allows you to mix the
if statement with HTML nicely:

<?php if ( expession) : ?>


<!-- HTML code here -->
<?php endif; ?>

The following example uses the if statement that shows the edit link if
the $is_admin is true:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP if Statement Demo</title>
</head>
<body>
<?php $is_admin = true; ?>
<?php if ( $is_admin ) : ?>
<a href="#">Edit</a>
<?php endif; ?>
<a href="#">View</a>
</body>
</html>

Since the $is_admin is true, the script shows the Edit link. If you change the
value of the $is_admin to false, you won’t see the Edit link in the output.

A common mistake with the PHP if statement


A common mistake that you may have is to use the wrong operator in
the if statement. For example:

<?php

$checked = 'on';
if( $checked = 'off' ) {
echo 'The checkbox has not been checked';
}

This script shows a message if the $checked is 'off'. However, the


expression in the if statement is an assignment, not a comparison:

$checked = 'off'Code language: PHP (php)

This expression assigns the literal string 'off' to the $checked variable and
returns that variable. It doesn’t compare the value of the $checked variable
with the 'off' value. Therefore, the expression always evaluates to true,
which is not correct.

To avoid this error, you can place the value first before the comparison
operator and the variable after the comparison operator like this:

<?php

$checked = 'on';
if('off' == $checked ) {
echo 'The checkbox has not been checked';
}

If you accidentally use the assignment operator (=), PHP will raise a
syntax error instead:

<?php

$checked = 'on';
if ('off' = $checked) {
echo 'The checkbox has not been checked';
}
Error:

Parse error: syntax error, unexpected '=' ...

Summary
 The if statement executes a statement if a condition evaluates to true.
 Always use curly braces even if you have a single statement to execute in
the if statement. It makes the code more obvious.

Introduction to PHP if-else statement


 The if statement allows you to execute one or more statements
when an expression is true:
<?php
 if ( expression ) {
 // code block
 }Code language: HTML, XML (xml)
 Sometimes, you want to execute another code block if
the expression is false. To do that, you add the else clause to
the if statement:
 <?php
 if ( expression ) {
 // code block
 } else {
 // another code block
 }Code language: HTML, XML (xml)
 In this syntax, if the expression is true, PHP executes the code block
that follows the if clause. If the expression is false, PHP executes the
code block that follows the else keyword.
 The following flowchart illustrates how the PHP if-else statement
works:

 The following example uses the if...else statement to show a
message based on the value of the $is_authenticated variable:
 <?php

 $is_authenticated = false;

 if ( $is_authenticated ) {
 echo 'Welcome!';
 } else {
 echo 'You are not authorized to access this page.'
 }Code language: HTML, XML (xml)
 In this example, the $is_authenticated is false. Therefore, the script
executes the code block that follows the else clause. And you’ll see
the following output:
 You are not authorized to access this [Link] language: JavaScript
(javascript)

 PHP if…else statement in HTML


 Like the if statement, you can mix the if...else statement with HTML
nicely using the alternative syntax:
 <?php if ( expression ): ?>
 <!--Show HTML code when expression is true -->
 <?php else: ?>
 <!--Show HTML code when expression is false -->
 <?php endif ?>Code language: HTML, XML (xml)
 Note that you don’t need to place a semicolon ( ;) after
the endif keyword because the endif is the last statement in the PHP
block. The enclosing tag ?> automatically implies a semicolon.
 The following example uses the if...else statement to show the logout
link if $is_authenticated is true. If the $is_authenticated is false, the script
shows the login link instead:
 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <title>PHP if Statement Demo</title>
 </head>
 <body>
 <?php $is_authenticated = true; ?>
 <?php if ($is_authenticated) : ?>
 <a href="#">Logout</a>
 <?php else: ?>
 <a href="#">Login</a>
 <?php endif ?>
 </body>
 </html>

Introduction to PHP for statement


The for statement allows you to execute a code block repeatedly. The
syntax of the for statement is as follows:

<?php

for (start; condition; increment) {


statement;
}Code language: HTML, XML (xml)

How it works.

 The start is evaluated once when the loop starts.


 The condition is evaluated once in each iteration. If the condition is true,
the statement in the body is executed. Otherwise, the loop ends.
 The increment expression is evaluated once after each iteration.

PHP allows you to specify multiple expressions in the start, condition,


and increment of the for statement.

In addition, you can leave the start, condition, and increment empty,
indicating that PHP should do nothing for that phase.

The following flowchart illustrates how the for statement works:


When you leave all three parts empty, you should use a break statement to
exit the loop at some point. Otherwise, you’ll have an infinite loop:

<?php

for (; ;) {
// do something
// ...

// exit the loop


if (condition) {
break;
}
}

PHP for statement example


The following shows a simple example that adds numbers from 1 to 10:
<?php

$total = 0;

for ($i = 1; $i <= 10; $i++) {


$total += $i;
}

echo $total;

Output:

55

How it works.

 First, initialize the $total to zero.


 Second, start the loop by setting the variable $i to 1. This initialization will
be evaluated once when the loop starts.
 Third, the loop continues as long as $i is less than or equal to 10. The
expression $i <= 10 is evaluated once after every iteration.
 Fourth, the expression $i++ is evaluated after each iteration.
 Finally, the loop runs exactly 10 iterations and stops once $i becomes 11.

Alternative syntax of the for statement


The for statement has the alternative syntax as follows:

for (start; condition; increment):


statement;
endfor;

The following script uses the alternative syntax to calculate the sum of 10
numbers from 1 to 10:

<?php

$total = 0;

for ($i = 1; $i <= 10; $i++):


$total += $i;
endfor;

echo $total;

Output:

55
Introduction to the PHP while statement
The while statement executes a code block as long as an expression is true. The syntax of
the while statement is as follows:

<?php

while (expression) {
statement;
}Code language: HTML, XML (xml)

How it works.

 First, PHP evaluates the expression. If the result is true, PHP executes the statement.
 Then, PHP re-evaluates the expression again. If it’s still true, PHP executes the statement
again. However, if the expression is false, the loop ends.

If the expression evaluates to false before the first iteration starts, the loop ends immediately.

Since PHP evaluates the expression before each iteration, the while loop is also known as
a pretest loop.

The while doesn’t require curly braces if you have one statement in the loop body:

<?php

while (expression)
statement;Code language: HTML, XML (xml)

However, it’s a good practice to always include curly braces with the while statement even
though you have one statement to execute.

The following flowchart illustrates how the while statement works:


PHP while loop example
The following example uses a while loop to add whole numbers from 1 to 10:

<?php

$total = 0;
$number = 1;

while ($number <= 10) {


$total += $number;
$number++;
}

echo $total;

Output:

55

The alternative syntax for the PHP while loop


The alternative syntax for the while statement is as follows:

<?php

while (expression):
statement;
endwhile;

The following uses the alternative syntax of the while statement to sum the whole numbers
from 1 to 10.

<?php

$total = 0;
$number = 1;

while ($number <= 10) :


$total += $number;
$number++;
endwhile;

echo $total;

Output:

55
PHP do…while

Introduction to PHP do…while loop statement


The PHP do...while statement allows you to execute a code block repeatedly
based on a Boolean expression. Here’s the syntax of the PHP do-
while statement:

<?php

do {
statement;
} while (expression);Code language: HTML, XML (xml)

Unlike the while statement, PHP evaluates the expression at the end of each
iteration. It means that the loop always executes at least once, even
the expression is false before the loop enters.

The following flowchart illustrates how the do...while statement works:


do…while vs. while
The differences between the do...while and while statements are:

 PHP executes the statement in do...while at least once, whereas it won’t


execute the statement in the while statement if the expression is false.
 PHP evaluates the expression in the do...while statement at the end of each
iteration. Conversely, PHP evaluates the expression in the while statement
at the beginning of each iteration.

PHP do…while loop statement example


In the following example, the code block inside the do...while loop
statement executes precisely one time.

<?php

$i = 0;
do {
echo $i;
} while ($i > 0);Code language: HTML, XML (xml)

The code inside the loop body executes first to display the variable $i.
Because the value of the $i is 0, the condition is met, the loop stops.

In the following example, the code block inside the do...while loop executes
ten times:
<?php

$i = 10;

do {
echo $i . '<br>';
$i--;
} while ($i > 0);

PHP foreach

Introduction to the PHP foreach statement


PHP provides you with the foreach statement that allows you to iterate over
elements of an array, either an indexed array or an associative array.

The foreach statement iterates over all elements in an array, one at a time.
It starts with the first element and ends with the last one. Therefore, you
don’t need to know the number of elements in an array upfront.

The following flowchart illustrates how the foreach statement works:

PHP foreach with indexed arrays


To iterate over all elements of an indexed array, you use the following
syntax:
<?php

foreach ($array_name as $element) {


// process element here
}

When PHP encounters a foreach statement, it assigns the first element of


the array to the variable following the as keyword ($element).

In each iteration, PHP assigns the next array element to


the $element variable. If PHP reaches the last element, the loop ends.

The following example uses the foreach statement to display elements of


the $colors array:

<?php

$colors = ['red', 'green', 'blue'];

foreach ($colors as $color) {


echo $color . '<br>';
}

Output:

red
green
blueCode language: plaintext (plaintext)

PHP foreach with an associative array


To iterate over elements of an associative array, you use the following
syntax:

<?php
foreach ($array_name as $key => $value) {
//process element here;
}

When PHP encounters the foreach statement, it accesses the first element
and assigns:

 The key of the element to the $key variable.


 The value of the element to the $value variable.

In each iteration, PHP assigns the key and value of the next element to
the variables ($key and $value) that follows the as keyword. If the last
element is reached, PHP ends the loop.
The following example illustrates how to use the foreach statement to
iterate over elements of the captials array:

<?php

$capitals = [
'Japan' => 'Tokyo',
'France' => 'Paris',
'Germany' => 'Berlin',
'United Kingdom' => 'London',
'United States' => 'Washington D.C.'
];

foreach ($capitals as $country => $capital) {


echo "The capital city of {$country} is $capital" . '<br>';
}

Output:

The capital city of Japan is Tokyo


The capital city of France is Paris
The capital city of Germany is Berlin
The capital city of United Kingdom is London
The capital city of United States is Washington D.C.

You might also like