PHP Notes 1 To 10

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

PHP:

Prerequisites: Basic understanding of Computer Programming, Internet, Database, and


MySQL
Introduction:

 The PHP Hypertext Preprocessor (PHP) is a programming language that allows


web developers to create dynamic content that interacts with databases.

 PHP is basically used for developing web based software applications.

 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

 PHP is a server side scripting language that is embedded in HTML / XHTML. It is


used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.

 Database access has been a prime focus of PHP development. It is integrated with
a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase,
Informix, and Microsoft SQL Server.

 PHP is pleasingly energetic in its execution, especially when compiled as an


Apache module on the Unix side.

 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.
 PHP Syntax is C-Like or Perl-like or JavaScript-like. PHP file extensions can be
.php, .php3, .phtml etc.

 PHP is an interpreted language, i.e., there is no need for compilation.

 PHP uses dynamic typing and hence PHP is far more forgiving. PHP is faster than
other scripting languages, for example, ASP and JSP.

 PHP supports both procedural and object oriented programming.

 PHP is free and an open source system. As on January 2019, PHP version is 7.3.1,
which is stable.

 PHP scripts are either embedded in XHTML documents or are in files that are
referenced by XHTML documents.

 All PHP code must be included inside one of the three special markup tags that
are recognised by the PHP Parser.

1. <?php PHP code goes here ?>


2. <? PHP code goes here ?>
3. <script language = “php”> PHP code goes here </script>
 A most commonly used tag is the <?php ... ?>
Common uses of PHP:
 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.

 PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.

 You add, delete, modify elements within your database through PHP.

 Access cookies variables and set cookies.

 Using PHP, you can restrict users to access some pages of your website.

 It can encrypt data.

Characteristics of PHP:
Five important characteristics that make PHP competent and powerful are:

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

PHP – Environment Setup


In order to develop and run PHP Web pages three vital components need to be installed
on our computer system.

 Web Server – PHP will work with virtually all Web Server software, including
Microsoft’s Internet Information Server (IIS) but then most often used is freely
available Apache Server.

 Database – PHP will work with virtually all database software, including Oracle
and Sybase but most commonly used is freely available MySQL database.

 PHP Parser – In order to process PHP script instructions a parser must be


installed to generate HTML output that can be sent to the Web Browser. This
tutorial will guide you how to install PHP parser on your computer.

Note: A PHP processor is now resident on most Web servers. WAMP, LAMP, XAMPP
are the currently used web server solution stacks.
Modes of Operation – PHP

 PHP processor has 2 modes of operation – COPY Mode and INTERPRET Mode.
 It takes a PHP document as input and produces XHTML document as output.
 When PHP processor finds XHTML code in the input file, it simply copies it to the
output file.
 When PHP processor encounters PHP script in the input file, it interprets it and
sends any output of the script to the output file.
 In either case, it is evident that the output of PHP script is XHTML file or an
embedded client-side script.
 Ex: Consider a PHP script is stored in a different file. It is brought to the XHTML
document with include construct, which takes the file name as it sparameter, as
shown below.
Include(“sample.php”);
 The include construct causes the contents of the file sample.php to be copied into
the document where the call appears.
 Here, the PHP interpreter changes from interpret to copy mode when an include
is encountered.

Sample Script in PHP - "Hello World"


<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result −

Hello, World!
 If you examine the HTML output of the above example, you'll notice that the PHP
code is not present in the file sent from the server to your Web browser. All of the
PHP present in the Web page is processed and stripped from the page; the only
thing returned to the client from the Web server is pure HTML output.

Example 1: Example 2:
<!DOCTYPE html> <!DOCTYPE>
<html> <html>
<body> <body>
<?php <?php
echo "My first PHP script!"; echo "<h2>Hello by PHP</h2>";
?> ?>
</body> </body>
</html> </html>
PHP – General syntactic Characteristics

1. PHP syntax and semantics are closely related to syntax and semantics of
JavaScript, Perl.
2. PHP code is embedded in XHTML documents by enclosing it between
<?php and ?> tags.
3. PHP interpreter changes from interpret to copy mode when an include is
encountered.
Ex: Include(“sample.php”);
4. All variables in PHP begin with $ sign. Variable names are like in many common
programming languages; a letter or an underscore followed by any number of
letters, digits, underscores.
Ex: $sum, $str, $_name
5. PHP variable names are case sensitive.

<?php
$book = 67;
print("Variable book is $book);
print("Variable BooK is $BooK);
?>

This will produce the following result:


Variable book is 67
Variable BooK is
6. PHP is whitespace insensitive.
7. PHP variables are not type declared and they have no intrinsic type. The type of a
variable is set every time it is assigned a value, taking on the type of that value.
8. PHP reserved words are not case sensitive. For ex: while, WHILE, While, WhiLE
etc. are all valid. Few of the reserved words include: and, break, do, global, new,
switch, virtual, static, false, function, if, return, extends, require, class,
continue, case, this, var etc.
9. PHP allows comments to be specified in 3 ways. They are Single-line comments
like # in perl; Single-line comments like // in C; Multi-line comments like /*…*/ in
many other programming languages. Among these, Perl-style comments are most
frequently used.

Ex: # This is a widely used comment


// This is a comment too
/* This is another way of comment
In PHP */
10. PHP statements are terminated with semicolon (;).

Ex: $greeting = "Welcome to PHP!";

11. Braces { } are used to form compound statements for control structures. Unless
used as body of a function, compound statements cannot be considered as blocks.
PHP –Primitives , Operations, Expressions

 PHP has 4 scalar types namely Boolean, integer, double and string;
has 2 compound types namely array and object ; 2 special types namely resource
and NULL.

Boolean − have only two possible values either true or false.

Integer − are whole numbers, without a decimal point, like 4195.

Double − are floating-point numbers, like 3.14159 or 49.1.

String − are sequences of characters, like 'PHP supports string operations.

Array − are named and indexed collections of other values.

Object − are instances of programmer-defined classes, which can package up


both other kinds of values and functions that are specific to the class.

Resource − are special variables that hold references to resources external to


PHP (such as database connections).

NULL − is a special type that only has one value: NULL.

PHP Variables:

 PHP variables are Perl-like.


 HP is dynamically typed and has no type declarations.
 There is no need to ever declare the type of a variable.
 The type of a variable is set every time it is assigned a value.
 Variables used before they are assigned have default values.
 An unassigned variable, sometimes called an unbound variable, has the value
NULL, which is the only value of NULL type.
 If an unbound variable is used in an expression, NULL is changed to a value that is
dictated by the context of the use. If the context specifies a number, NULL is
changed to 0; if the context specifies a string, NULL is changed to an empty string.
 If we wish to be informed when an unbound variable is referenced, we may call
the error_reporting() function with level 15, at the beginning of the script.
Ex: error_reporting(15);
 Using IsSet() function, a variable is tested to determine if it currently has a value.
Ex: IsSet($book) returns TRUE if $book currently has a non-NULL value,
FALSE otherwise.
 The value of a variable is the value of its most recent assignment.
 A variable once is assigned a value, retains it until either it is assigned a new value
or it is set back to the unassigned state, which is done with unset() function.
Integer Type:

 PHP has single integer type named integer.


 Size of integer is of word size like long int in C.
Ex: $int_var = 12345;
$another_int = -12345 + 12345;
 Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16)
format. Decimal format is the default.

Double Type:
 Doubles in PHP corresponds to the double type of C language.
 Doubles include a decimal point, exponent, or both.
Ex: $many = 2.2800;
$many_2 = .2115;

Boolean Type:
 The only two possible values for Boolean type are TRUE or FALSE, which are
case insensitive.
if (TRUE)
print("This will always print");
else
print("This will never print");
 Expressions of other types can be used in Boolean context. If we use non-
Boolean expression in Boolean context, we should its interpretation.
 Here are the rules for determine the "truth" of any value not already of the
Boolean type:
a) If the value is a number: it is FALSE if exactly equal to zero and TRUE
otherwise.
b) If the value is a string: it is FALSE if the string is empty (has zero
characters) or is the string "0", and is TRUE otherwise.
c) Values of type NULL are always FALSE.
d) If the value is an array, it is FALSE if it contains no other values, and it is
TRUE otherwise. For an object, containing a value means having a member
variable that has been assigned a value.
e) Valid resources are TRUE (although some functions that return resources
when they are successful will return FALSE when unsuccessful).
f) Don't use double as Booleans.
 Each of the following variables has the truth value embedded in its name when
it is used in a Boolean context.

a) $true_num = 3 + 0.14159; b) $true_str = "Tried and true";

c) $true_array[49] = "An array element"; d) $false_array = array();

e) $false_null = NULL; f) $false_num = 999 - 999;

g) $false_str = "";
String Type:

 Characters in PHP are single bytes.


 There is no character type in PHP.
 A single character data value is represented as a string of length of 1.
 Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences, like escape sequences.
 Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
$string_3 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

 Example:

<?php
$sum = 2003;
$literally = 'My Value of sum is:$sum';
print($literally);
$literally = "My Value of sum is:$sum";
print($literally);
?>
This will produce following result −

My Value of sum is:$sum


My Value of sum is:2003

 There are no artificial limits on string length – can have any length within the
bounds of available memory.
 Strings that are delimited by double quotes (as in "this") are preprocessed in the
following two ways by PHP:
a) Certain character sequences beginning with backslash (\) are replaced with
special characters
b) Variable names (starting with $) are replaced with string representations of their
values.

The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
PHP Operators:
PHP language supports following type of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

Arithmetic Operators:
 PHP has the usual collection of arithmetic operators, like C- language, with the
usual meanings.

 Assume variable A holds 10 and variable B holds 20.


Operator Description Example

+ Adds two operands A + B will


give 30

- Subtracts second operand from the first A - B will


give -10

* Multiply both operands A * B will


give 200

/ Divide numerator by denominator. Any operation on integers that B / A will


results in overflow produces a double give 2

% Modulus Operator and remainder of after an integer division. The B % A will


operands of the % operator are expected to be integers. If any of give 0
them or both are not integers, then they are changed to integers

++ Increment operator, increases integer value by one A++ will give


11

-- Decrement operator, decreases integer value by one A-- will give


9

 In addition, it supports functions for base conversions, computing logarithms,


trigonometric calculations.
 PHP has a large number of predefined functions that operate on numeric values.
Some of the most useful of them are as below.

Function Parameter Type Return Value


floor() Double Rounds a number down to the nearest integer.
ceil() Double Rounds a number up to the nearest integer.
round() Double Nearest integer. Rounds a floating-point number.
srand() Integer Initializes a random number generator with the
parameter. The srand() function seeds the random
number generator, rand()
rand() Two numbers A pseudo random number greater than the first
(Integer or Double) parameter and smaller than the second parameter.
abs() Number Absolute value of the parameter.
(Integer or Double)
min() One or more numbers Smallest. Returns the lowest value in an array, or the
(Integer or Double) lowest value of several specified values.
max() One or more numbers Largest. Returns the highest value in an array, or the
(Integer or Double) highest value of several specified values.

echo(floor(-5.9)); -6
echo(floor(0.60)); 0
echo(floor(5.1)); 5
echo(floor(-5.1)); -6

echo(ceil(-5.9)); -5
echo(ceil(0.60)); 1
echo(ceil(5.1)); 6
echo(ceil(-5.1)); -5

echo(round(0.50)); 1
echo(round(0.49)); 0
echo(round(-4.40)); -4
echo(round(-4.60)); -5

srand(10); 10

echo(rand(10,100)); 36 // some random number between 10 and 100

echo(abs(-3.6)); 3.6

echo(max(22,14,68,18,15); 68
echo(max(array(44,16,81,12))); 81

echo(min(22,14,68,18,15)); 14
echo(min(array(44,16,81,12))); 12
String Operations:
 The only string operator is the concatenation operator specified with a period (.)
 Strings variables can be treated like arrays for access to individual cjharacters.
 The position of a character in s string, relative to zero, can be specified in braces
immediately after the variable’s name.
Ex: “book”, $str{3} is “k”
 PHP includes many functions that operate on strings. Some of the most commonly
used of these are as below.
Function Parameter Type Return Value
strlen() A string Number of characters in the string. Length of the
string.
strcmp() Two strings Compares two strings (case-sensitive). Zero if
strings are identical, negative number if the first
string belongs before second string (in ASCII
sequence), positive number if the second string
belongs before the first string.
strpos() Two strings Returns the position of the first occurrence of a
string inside another string (case-sensitive)
substr() A string and an The substring of the string parameter, starting
integer from the position indicated by the second
parameter.
chop() A string, Removes whitespace characters from the right
Characterlist end of a string. Second parameter specifies the
characters to be removed.
trim() A string, Removes whitespace characters from both sides
Characterlist of a string. Second parameter specifies the
characters to be removed.
ltrim() A string, Removes whitespace characters from the left
Characterlist side of a string. Second parameter specifies the
characters to be removed.
strtolower() A string Converts a string to lowercase letters

strtoupper() A string Converts a string to uppercase letters

echo strlen("Hello"); 5

echo strcmp("Hello world!","Hello world!"); 0 // strings are identical

echo strpos("I am in AWP Class, I am in AWP Classtwo!","AWP"); 8

echo substr("Hello world",6); world

echo chop(“Hello World!","World!"); Hello

echo trim(“Hello World!","Hed!"); llo Worl

echo ltrim(“Hello World!”,"Hello"); World!


echo strtolower("Hello WORLD."); hello world.
echo strtoupper("Hello WORLD!"); HELLO WORLD!

You might also like