PHP UNIT 01-Notes PDF
PHP UNIT 01-Notes PDF
PHP UNIT 01-Notes PDF
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.
Why PHP ?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
1 4 PHP
3 module
Apache
2
1: Client from browser send HTTP request (with POST/GET
variables)
2: Apache recognizes that a PHP script is requested and sends the
request to PHP module
3: PHP interpreter executes PHP script, collects script output and
sends it back
4: Apache replies to client using the PHP script output as HTML
output
Characteristics ofPHP OR Features of PHP
The main features of php is; it is open source scripting language so you can free
download this and use. PHP is a server site scripting language. It is open source
scripting language. It is widely used all over the world. It is faster than other scripting
language. Some important features of php are given below;
1. Simple
2. Faster
3. Interpreted
4. Open Source
5. Case Sensitive
6. Simplicity
7. Efficiency
8. Platform Independent
9. Security
10. Flexibility
11. Familiarity
12. Error Reporting
13. Loosely Typed Language
14. Real-Time Access Monitoring
Simple
It is very simple and easy to use, compare to other scripting language, this is widely
used all over the world.
Interpreted
Faster
Open Source
Open source means you do not need to pay for using php, you can free download and
use.
Platform Independent
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.
Case Sensitive
PHP is case sensitive scripting language at time of variable declaration. In PHP, all
keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
Error Reporting
PHP have some predefined error reporting constants to generate a warning or error
notice.
PHP provides access logging by creating the summary of recent accesses for the user.
PHP supports variable usage without declaring its data type. It will be taken at the
time of the execution based on the type of data it has on its value.
Alternatives to PHP
XAMPP
XAMPP is an open source software developed by Apache friends. XAMPP software
package contains Apache distributions for Apache server, MariaDB, PHP, and Perl. And
it is basically a local host or a local server. This local server works on your own desktop
or laptop computer. The use of XAMPP is to test the clients or your website before
uploading it to the remote web server. This XAMPP server software gives you the
suitable environment for testing MYSQL, PHP, Apache and Perl projects on the local
computer.
A Apache server,
M MariaDB,
P PHP and
P Perl.
The Cross-platform usually means that it can run on any computer with any
operating system. MariaDB is the most famous database server and it is developed by
MYSQL team. PHP usually provides a space for web development. PHP is a server-side
scripting language. And the last Perl is a programming language and is used to develop a
web application.
The XAMPP installation process is very simple and fast. Once XAMPP is
installed on your local computer it acts as a local server or localhost. You can test the
websites before uploading it to the remote web server. This XAMPP server software
gives you a suitable environment for testing MYSQL, PHP, Apache and Perl
applications on a local computer.
Step 2
Once the software is downloaded, you have to install by double click the .exe file
Step 3
Once the file is executed, a setup window appears. In the setup file, select the
components that are required. For eg (if you want to install WordPress on XAMPP, the
required components are MySQL, Apache, PHPMyAdmin).
Step 4
Next step is to choose the folder where the file is to be located. It is recommended to
choose the default “C drive” and then click “Next” button.
Step 5
Clicking on the next your installation process will be started. The setup wizard will
unpack and install all the selected components and will save them to their designated
directory. The installation process takes a couple of minutes to complete.
Step 6
Once the installation process is completed, click on the “Finish” button.
Step 7
Once done, the XAMPP icon will appear on your desktop or start menu. By double-
clicking the XAMPP icon, XAMPP control panel window appears.
Step 8
In the XAMPP control panel, click the necessary modules that are required for you to
work. You can start the modules by clicking the “Start” button under “Actions”. You
will be able to see the initiated modules highlighted in green. For example, if you are
using WordPress platform then the required components are Apache and MYSQL.
Note: If you cannot start a module as a result of the error, then it will be indicated with a
red font. They will provide you with a detailed report to identify the cause of an error.
Step 9
Then by clicking the Apache or any “Admin” button in the XAMPP control panel, you
will be able to configure each module settings separately.
Step 10
That’s it, now in your web browser type localhost and you will be able to see a splash
screen of XAMPP. Here you have to choose a language which you understand.
The code above is simply HTML, with just a bit of PHP that prints out
today's date using the built-in date function. As mentioned above, all of the
plain HTML in the code above will be ignored by the PHP compiler and
passed through to the web browser untouched.
Integrating PHP and HTML is really very simple. Just remember that at its
core, a PHP script is just an HTML page with some PHP sprinkled through
it. If you want, you can create a PHP script that only has HTML in it and
no <?php ?> tags, and it will work just fine.
By Using sqrt():
<?php
echo(sqrt(25));
?>
By Longer Method:
<?php
function my_sqrt($n)
{
$x = $n;
$y = 1;
while($x > $y)
{
$x = ($x + $y)/2;
$y = $n/$x;
}
return $x;
}
print(my_sqrt(16)."\n");
?>
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers
can be specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or
octal (base 8 - prefixed with 0) notation, optionally preceded by a sign (- or +).
The var_dump() function is used to display structured information (type and value)
about one or more variables.
Example
Run this code
<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>"
$b = -123; // a negative number
var_dump($b);
echo "<br>";
Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To
use binary notation precede the number with 0b (e.g. $var = 0b11111111;).
PHP Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters and it can be as large as
up to 2GB (2147483647 bytes maximum). The simplest way to specify a string is
to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double
quotes ("Hello world!").
Example
Run this code
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
Example
Run this code
<?php
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>
PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
Example
Run this code
<?php
// Assign the value TRUE to a variable
$show_error = true;
var_dump($show_error);
?>
PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to
aggregate a series of related items together, for example a set of country or city
names.
An array is formally defined as an indexed collection of data values. Each index
(also known as the key) of an array is unique and references a corresponding value.
Example
Run this code
<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
$color_codes =
array( "Red" =>
"#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>
You will learn more about arrays in PHP Array tutorial.
PHP Objects
An object is a data type that not only allows storing data but also information on,
how to process that data. An object is a specific instance of a class which serve as
templates for objects. Objects are created based on this template via the new
keyword.
Every object has properties and methods corresponding to those of its parent class.
Every object instance is completely independent, with its own properties and
methods, and can thus be manipulated independently of other objects of the same
class.
Here's a simple example of a class definition followed by the object creation.
Example
Run this code
<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";
// methods
function
show_greeting(){ return
$this->str;
}
}
Tip: The data elements stored within an object are referred to as its properties and
the information, or code which describing how to process the data is called the
methods of the object.
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of
type NULL is a variable without any data. NULL is the only possible value of type
null.
Example
Run this code
<?php
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically
assigned a value of null. Many novice PHP developers mistakenly considered
both $var1 = NULL; and $var2 = ""; are same, but this is not true. Both variables
are different — the $var1 has null value while $var2indicates no value assigned to
it.
PHP Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database
connections.
Example
Run this code
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
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.
Syntax
define(name, value, case-insensitive)
Parameters:
ex:
define("PI","3.142",false);
define("PI","3.142",true);
<?php
define("PI","3.142",false);
$radius="2";
?>
Explain comments in PHP
Comments in PHP
o A comment is something which is ignored and not read or executed by
PHP engine or the language as part of a program and is written to
make the code more readable and understandable.
o These are used to help other users and developers to describe the code
and what it is trying to do.
o It can also be used in documenting a set of code or part of a program.
o PHP supports two types of comment:
Single Line Comment: As the name suggests this is single line
or short relevant explanations that one can add in the code. To
add this, we need to begin the line with (//) or (#).
Example:
<?php
?>
Output:
hello world!!!
echo $geek;
?>
Output:
hello world!
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array 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
The PHP assignment operators are used with numeric values to write a value toa
variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the
expression on the right
x += y x=x+y Addition
x %= y x=x% y Modulus
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
<?php
$x = 50;
$y = "500";
var_dump($x === $y); // returns false because types are not equal
?>
The PHP increment operators are used to increment a variable's value. The PHP
decrement operators are used to decrement a variable's value.
Ex:
<?php
$x = 100;
$y = 50;
PHP has two operators that are specially designed for strings.
Flow Diagram:
2. while loop: The while loop is also an entry control loop like for loops i.e., it
first checks the condition at the start of the loop and if its true then it enters
the loop and executes the block of statements, and goes on executing it as long
as the condition holds true.
Syntax:
while (if the condition is true) {
// code is executed
}
Example:
<?php
$num = 2;
$num += 2;
?>
Flowchart:
3. do-while loop: This is an exit control loop which means that it first enters
the loop, executes the statements, and then checks the condition. Therefore, a
statement is executed at least once on using the do…while loop. After
executing once, the program is executed as long as the condition holds true.
Syntax:
do {
//code is executed
} while (if condition is true);
Example:
<?php
$num = 2;
do {
$num += 2;
Flowchart:
4. foreach loop: This loop is used to iterate over arrays. For every counter of
loop, an array element is assigned and the next counter is shifted to the next
element.
Syntax:
foreach (array_element as value) {
//code to be executed
}
Example:
<?php
?>
Output:
10 20 30 40 50 60 Ram Laxman Sita
if statement
if…else statement
if…elseif…else statement
switch statement
$x = 12;
if ($x > 0) {
Output:
The number is positive
Flowchart:
?>
Output:
The number is negative
Flowchart:
$x = "August";
if ($x == "January") {
else{
?>
Output:
Happy Independence Day!!!
Flowchart:
Flowchart:
Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of
writing if…else, called Ternary Operators. The statement uses a question mark (?)
and a colon (:) and takes three operands: a condition to check, a result for TRUE
and a result for FALSE.
Syntax:
(condition) ? if TRUE execute this : otherwise execute this;
Example:
<?php $x = -12;
Output:
The number is negative
PHP Functions
PHP function is a piece of code that can be reused many
times. It can take input as argument list and return value.
There are thousands of built-in functions in PHP.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the
syntax to declare user-defined functions.
Syntax
function functionname()
{
//code to be executed
}
PHP Functions Example
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>
// will be considered
defGeek("Adam");
?>
Output:
Ram is 15 years old
Adam is 12 years old
In the above example, the parameter $num has a default value 12, if we do not pass
any value for this parameter in a function call then this default value 12 will be
considered. Also the parameter $str has no default value , so it is compulsory.
pro(2, 3, 5);
?>
Output:
The product is 30
}
// storing the returned value
?>
Output:
The product is 30
// pass by value
function val($num) {
$num += 2;
return $num;
// pass by reference
function ref(&$num) {
$num += 10;
return $num;
}
$n = 10;
val($n);
ref($n);
?>
Output:
The original value is still 10
The original value changes to 20
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output:
Today's date is :05/12/2017
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
<?php
echo "The time is " . date("h:i:sa");
?>
Note that the PHP date() function will return the current
date/time of the server!
Note:
If the time you got back from the code is not correct, it's probably because your server is in another
country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone you
want to use.
The example below sets the timezone to "America/New_York", then outputs the current time in the
specified format:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Example:
<?php
// PHP code to return absolute value.
function absolute($degree)
{
return (abs($degree));
}
// Driver Code
$number = -8.4;
echo(absolute($number));
?>
Output : 8.4
2. pi() :
This function returns the value of pi. The named constant M_PI is identical to pi().
Syntax :
pi();
Example :
<?php
# PHP function to convert degree to radian value.
echo(pi());
?>
Output :
3.1415926535898
3.decbin() :
This function convert a decimal number to binary number.
Syntax :
pi();
Example :
<?php
# PHP function to convert a decimal number to binary number.
echo(decbin(20));
?>
Output : 101
4.exp() :
This function calculate exponential of e
5. floor() :
This function takes numeric value as argument and returns the next lowest integer.
value (as float) by rounding down value if necessary
Syntax :
floor($number);
Example:
<?php
echo(floor(0.60)."\n");
echo(floor(5)."\n");
echo(floor(-5.9));
?>
Output :
0
5
-6
6. ceil() :
This function takes numeric value as argument and returns the next highest integer
value by rounding up value if necessary.
Syntax :
ceil($number);
Example :
<?php
echo(ceil(0.60)."\n");
echo(ceil(-5.9));
?>
Output:
1
-5
7. round() :
This function takes numeric value as argument and returns the next highest integer
value by rounding up value if necessary.
Syntax :
Example :
<?php
echo(round(1.95583, 2)."\n");
echo(round(1241757, -3)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_UP)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_DOWN)."\n");
echo(round(9.5, 0, PHP_ROUND_HALF_EVEN)."\n");
echo round(9.5, 0, PHP_ROUND_HALF_ODD);
?>
Output :
1.96
1242000
10
9
10
9
while($n>0)
{
$fact=$fact*$n;
$n--;
}
echo "$fact";
}
?>
</form>
</body>
</html>
When a variable is accessed outside its scope it will cause PHP error Undefined
Variable.
<?php
function calculate_count() {
$count = 5;
echo $count++;
?>
Local variables will be destroyed once the end of the code block is reached. Hence
the same named variables can be declared within different local scopes.
As its name, the global scope provides widespread access to the variable declared
in this scope. Variables in global scope can be accessed from anywhere from
outside a function or class independent of its boundary.
PHP global variables can be defined by using global keyword. If we want to use
global variables inside a function, we have to prefix the global keyword with the
variable. The following code shows a code block to learn how to use the global
keyword with a PHP variable to declared it as a global variable.
<?php
$count = 0;
function calculate_count()
{ global $count;
calculate_count();
echo $count;
?>
PHP has a predefined superglobal variable called $GLOBALS. It is an associative
array with the name of the variable as key and value as the array element. We can
use this array variable to add an array of PHP variables in a global scope.
Let us change the above example with the global keyword by using $GLOBALS
superglobal to access the variable in global scope.
<?php
$count = 0;
function calculate_count() {
calculate_count();
echo $count;
?>
A static variable is again a variable with local scope. But the difference with the
regular local variable is that it is not destroyed outside the scope boundary. A
variable can be defined by using the ‘static’ keyword inside a function.
A static variable does not lose its value when the program execution goes past the
scope boundary. But it can be accessed only within that boundary. Let me
demonstrate it using the following example code,
The above counter function has the static variable ‘count’ declared within its local
scope. When the function execution is complete, the static count variable still retains
its value for further computation. Every time the counter function is called, the value
of count is incremented. The count value is initialized only once on the first call.
<?php
function counter()
static $count = 0;
echo $count;
$count++;
?>
Function parameters (arguments) are local variables defined within the local scope
of the function on which it is used as the argument.