Chapter 2 WP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

CHAPTER 2

Brief history of PHP:


The name PHP stands for Hypertext Preprocessor and denotes a server-side scripting language,
which suggests that applications are written thereon run on web servers and don’t depend upon
the online browser.
Html: to create well formatted document in the year 1991 Tim Berners lee developed html. But it
was not able to create more appealing websites. Hence we use CSS.
CSS: To create more appealing websites in the year 1996 Hakon Wium Lie developed CSS. But it
was not able to create interactive websites. Hence we use Java Script.
Java script: To add behavior or interactivity to web elements in the year 1996 Brendon Each

Advantages of PHP:

8|Page
 The most important advantage of PHP is that it’s open-source and free from cost. It can be
downloaded anywhere and is readily available to use for events or web applications.
 It is platform-independent. PHP-based applications can run on any OS like UNIX, Linux,
Windows, etc.
 Applications can easily be loaded which are based on PHP and connected to the database.
It’s mainly used due to its faster rate of loading over slow internet speed than other
programming language.
 It has less learning curve because it is simple and straightforward to use. Someone familiar
with C programming can easily work on PHP.
 It is more stable for a few years with the assistance of providing continuous support to
various versions.
 It helps in reusing an equivalent code and not got have to write lengthy code and
sophisticated structure for events of web applications.
 It helps in managing code easily.
 It has powerful library support to use various function modules for data representation.
 PHP’s built-in database connection modules help in connecting databases easily reducing
trouble and time for the development of web applications and content-based sites.
 The popularity of PHP gave rise to various communities of developers, a fraction of which
may be potential candidates for hire.
 Flexibility makes PHP ready to effectively combine with many other programming
languages in order that the software package could use foremost effective technology for
every particular feature.

Disadvantages of PHP:

 It is not that secure due to its open-source, because the ASCII text file is often easily available.
 It is not suitable for giant content-based web applications.
 It has a weak type, which can cause incorrect data and knowledge to users.
 PHP frameworks got to learn to use PHP built-in functionalities to avoid writing additional code.
 Using more features of PHP framework and tools cause poor performance of online
applications.
 PHP doesn’t allow change or modification in the core behavior of online applications.
 The PHP frameworks aren’t equivalent in behavior so does their performance and features.
 While PHP may be a powerful tool supported by an outsized community and plentiful reference
documentation, there are easier programming languages for web apps.
 It is widely believed by the developers that PHP features a poor quality of handling errors. PHP
lacks debugging tools, which are needed to look for errors and warnings. PHP has less number of
debugging tools in comparison to other programming languages.
 It’s highly tough to manage because it’s not competent modular. It already imitates the features
of the Java language.

Embedding PHP Code in Webpages:

9|Page
A PHP code can be written in 3 ways

1. Without any HTML markups


2. Embedding HTML markups in PHP code
3. Embedding PHP code in HTML.

1. Without any HTML markups:


<?php
$a=10;
$b=10;
$c=$a+$b;
echo("The addition of a and b is ". $c);
?>
Output :
The addition of a and b is 20

2. Embedding HTML markups in PHP code:


<?php
echo "<html>";
echo "<h1> welcome </h1>" ;
echo "</html>" ;
?>
Output:
welcome

3. Embedding PHP code in HTML:


<html>
<body>
<?php
echo "Your first PHP code";
?>
</body>
</html>
Output:
Your first PHP code

LAMP stack:
A LAMP stack is a bundle of four different software technologies that developers use to build
websites and web applications. LAMP is an acronym for the operating system, Linux; the web
server, Apache; the database server, MySQL; and the programming language, PHP. All four of
these technologies are open source, which means they are community maintained and freely
available for anyone to use. Developers use LAMP stacks to create, host, and maintain web
content. It is a popular solution that powers many of the websites you commonly use today.

10 | P a g e
1. Linux: Linux started in 1991. It sets the foundation for the stack model. All other layers
are run on top of this layer.
It is an open-source and free operating system. It is endured partly because it's flexible,
and other operating systems are harder to configure.
2. Apache: The second layer consists of web server software, typically Apache Web Server.
This layer resides on top of the Linux layer.
Apache HTTP Server is a free web server software package made available under an
open-source license. It used to be known as Apache Web Server when it was created in
1995.
It offers a secure and extendable Web server that's in sync with current HTTP standards.
Web servers are responsible for translating from web browsers to their correct website.
3. MySQL: MySQL is a relational database management system used to store application
data. It is an open-source and keeps all the data in a format that can easily be queried with
the SQL language.
SQL works great with well-structured business domains, and a great workhorse that can
handle even the most extensive and most complicated websites with ease.
MySQL stores details that can be queried by scripting to construct a website. MySQL
usually sits on top of the Linux layer alongside Apache. In high-end configurations,
MySQL can be offloaded to a separate host server.
4. PHP: The scripting layer consists of PHP and other similar web programming languages.
The PHP open-source scripting language works with Apache to create dynamic web
pages. We cannot use HTML to perform dynamic processes such as pulling data out of a
database.
To provide this type of functionality, we drop PHP code into the parts of a page that you
want to be dynamic. Websites and Web Applications run within this layer.
PHP is designed for efficiency. It makes programming easier and allowing to write new
code, hit refresh, and immediately see the resulting changes without the need for
compiling.

11 | P a g e
Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php

// PHP code goes here

?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

PHP Case Sensitivity


In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

Look at the example below; only the first statement will display the value of the $color variable!
This is because $color, $COLOR, and $coLOR are treated as three different variables:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
12 | P a g e
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
Comments can be used to:
 Let others understand your code
 Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code

<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
?>
</body>
</html>

Syntax for multiple-line comments:

<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>

Using comments to leave out parts of the code:

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

13 | P a g e
What is Echo in PHP?

In PHP, Echo acts as a statement that is used to show the output. It does not return any value and
has the ability to pass multiple strings split by comma (,) in echo. We can use the Echo statement
with and without parentheses, and it is faster in nature.

What is Print in PHP?

In PHP, the Print statement is also used to show the output. We can use it as an alternative to
Echo. However, it is slower than Echo and returns an integer value 1. Also, in the Print statement
we cannot pass multiple arguments.

Difference between Echo and Print in PHP


S.No. Echo Statement Print Statement

In Echo, we can pass multiple arguments separated by In Print, we cannot pass multiple
1. commas. arguments.

In Echo, we can exhibit the outputs of one or more Through the Print statement, we can only
2. strings separated by commas. show the strings.

Print can also be used with or without


3 Echo can be used with or without parentheses
parentheses.

It always returns the integer value that is


4. It never returns any value.
1.

This statement is fast as compared to the print It is slow as compared to the echo
5. statement. statement.

14 | P a g e
Creating (Declaring) PHP Variables:
Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5. When you assign a text
value to a variable, put quotes around the value. Unlike other programming languages, PHP has no
command for declaring a variable. It is created the moment you first assign a value to it.

Naming PHP Variables:

A variable can have a short name (like x and y) or a more descriptive name (age, car name, total
volume).

Rules for naming 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)

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

<?php
$txt = "Computer Engg.";
echo "Diploma in $txt !";
?>

The following example will produce the same output as the example above:
<?php
$txt = "Computer Engg.!";
echo "Diploma in " . $txt . "!";
?>
The following example will output the sum of two variables:
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

15 | P a g e
We do not have to tell PHP which data type the variable is. PHP automatically associates a data type to
the variable, depending on its value. Since the data types are not set in a strict sense, you can do things
like adding a string to an integer without causing an error.

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:

 local
 global
 static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

<?php

$x = 5; // global scope

function myTest() {

// using x inside this function will generate an error

echo "<p>Variable x inside function is: $x</p>";

myTest();

echo "<p>Variable x outside function is: $x</p>";

?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

<?php

function myTest() {

$x = 5; // local scope

echo "<p>Variable x inside function is: $x</p>";

myTest();

// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";

16 | P a g e
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

<?php

function myTest() {

static $x = 0;

echo $x;

$x++;

myTest();

myTest();

myTest();

?>

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

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.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

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

<?php

define ("COMPUTER", "Welcome to computer engg.!");

echo COMPUTER;

?>

17 | P a g e
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 (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

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;

?>

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: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base
2) notation

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);

18 | P a g e
?>

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

<?php

$x = 10.365;

var_dump($x);

?>

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

$x = true;

$y = false;Booleans are often used in conditional testing. You will learn more about conditional testing in
a later chapter of this tutorial.

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type and
value:

<?php

$cars = array("Volvo","BMW","Toyota");

var_dump($cars);

?>

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the class, but
each object will have different values for the properties.

Let's assume we have a class named Car. A Car can have properties like model, color, etc. We can define
variables like $model, $color, and so on, to hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the properties.

If you create a __construct() function, PHP will automatically call this function when you create an object
from a class.
19 | P a g e
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.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

<?php

$x = "Hello world!";

$x = null;

var_dump($x);

?>

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

PHP String Literals:

A string literal is the notation for representing a string value within the text of a computer program. In
PHP, strings can be created with

 single quotes,
 double quotes
 heredoc
 nowdoc

Single quote vs double quote

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify
string in PHP.

 We can’t parse the data in this whereas double quote is said to be as interpreter.

Example:

<?php

$number=500;

Echo ”$number”;

Echo ’$number’

?>

Output:
20 | P a g e
500

$number

 We can’t use single quote inside single quote or double quote inside double quote.
 We can use single quote inside double quote or double quote inside single quote.
 To use single quote inside double or vice versa we use escape sequence\’ or \\.

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
 Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

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

PHP Comparison Operators

The 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

21 | P a g e
<> 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 equal to $x >= $y Returns true if $x is greater than or


equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than or equal
to $y

<=> Spaceship $x <=> $y Returns an integer less than, equal to,


or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.

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

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

22 | P a g e
== 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

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result Show it

?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.

The value of $x is expr2 if expr1 = TRUE.

The value of $x is expr3 if expr1 = FALSE

?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.

The value of $x is expr1 if expr1 exists, and is not NULL.

If expr1 does not exist, or is NULL, the value of $x is expr2.

PHP Array:

An array stores multiple values in one single variable:

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

An array can hold many values under a single name, and you can access the values by referring to an
index number.

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

23 | P a g e
PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can
use conditional statements in your code to do this.

In PHP we have the following 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

PHP - The if Statement

The if statement executes some code if one condition is true.

<?php

$a=20;

$b=10;

if($a>$b)

echo "A is greater than B";

?>

The IF-ELSE Statement

The if...else statement executes some code if a condition is true and another code if that condition is
false

<?php

$a=20;

$b=10;

if($a>$b)

echo "A is greater than B";

else

echo "B is greater than B";

}
24 | P a g e
?>

The if...elseif...else Statement

The if...elseif...else statement executes different codes for more than two conditions.

<?php

$t = date("H");

if ($t < "10") {

echo "Have a good morning!";

} elseif ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

PHP switch Statement:

Use the switch statement to select one of many blocks of code to be executed

<?php

$favcolor = "red";

switch ($favcolor) {

case "red":

echo "Your favorite color is red!";

break;

case "blue":

echo "Your favorite color is blue!";

break;

case "green":

echo "Your favorite color is green!";

break;

default:

echo "Your favorite color is neither red, blue, nor green!";

?>
25 | P a g e

You might also like