Unit 1
Unit 1
1 Early Beginnings
PHP was created in 1994 by Rasmus Lerdorf. Originally, it stood for "Personal Home
Page", but it was later changed to "Hypertext Preprocessor".
2 PHP 3 and 4
The first official release of PHP was PHP 3, which added additional features and
improved functionality. PHP 4, released in 2000, introduced a new extension model.
4. Embedded in HTML: PHP code can be embedded directly within HTML, making it
easy to mix server-side logic with HTML code. This integration facilitates the creation of
dynamic web pages.
5. Extensive Library Support: PHP has a vast collection of built-in functions and libraries
that simplify common tasks, such as database access, file manipulation, and more.
6. Database Support: PHP supports a wide range of databases, including MySQL,
PostgreSQL, SQLite, and more. It makes it easy to connect to databases and perform
operations like querying and updating data.
Features of PHP
Database Integration Server Compatibility Scalability
PHP has built-in support for It is compatible with most PHP provides great
working with various servers used today, scalability for web
databases, such as MySQL, including Apache, Nginx, applications, making it
PostgreSQL, and and Microsoft IIS. suitable for small personal
MongoDB. websites to large enterprise
systems.
PHP vs Other Programming
Languages
Flexibility
PHP is known for its flexibility and ability to be embedded into HTML, unlike many
other programming languages.
Performance
While PHP is a server-side scripting language, it offers great performance and can
handle a significant amount of web traffic.
INSTALLATION
5. Double-click on the downloaded file
6. Click on the Next button
7. Select the drive where you want to install
8. Click on the Next button until you get the finished button
9. Click on the Finish button
Setting up a PHP Development
Environment
1 Web Server
Choose a web server that best fits your needs, such as Apache or Nginx.
2 Database
Select a compatible database, like MySQL, to store and manage your PHP application data.
Adjusting PHP settings can significantly Configuring PHP settings includes ensuring
impact the performance of your web that security measures, such as input validation
applications. Address memory limits, error and error handling, are properly implemented.
reporting, and execution time to optimize This helps to protect your system from
performance. potential vulnerabilities.
Embedding PHP Code in HTML
1 Script Tags 2 Inline PHP
Utilize PHP code within HTML by Embed PHP code directly within the
encapsulating it within opening and HTML body to generate dynamic
closing script tags, allowing for content and leverage PHP's powerful
seamless integration of dynamic capabilities for enhancing web pages.
functionality.
COMMON USES OF PHP
<?php
Print “WELCOME”;
Print “<br>”;
$x=100;
Print $x;
?>
// php code
?>
The default file extension for PHP files is
".php".
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result –
Hello, World
All PHP code must be included inside one of the
three special
markup tags,are recognized by the PHP Parser.
For example,
<?php
echo "This is some text with spaces preserved.";
?>
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.
Any text between // and the end of the line will be ignored (will not be executed).
/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";
TYPES OF ERRORS: Mistake or fault occurs in a program is called
error. There are basically 4 types of errors in PHP:
1. Notice
2. Warning
3. Fatal Error
4. Parse Error
Notice
the error occurs when you try to access the undefined variable, and
then produce a notice error.
Example
<?php
$a="Uday ";
echo "Notice Error !!";
echo $b;
?>
warning
The main reason for warning errors is to include a missing file or
using the incorrect number of parameters in a function.
Example:
<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
fatal error
If you are trying to access the undefined functions, then the
output is a fatal error.
Example
<?php
function fun1(){ fun2();
echo "Uday Kumar"; echo "Fatal Error !!";
} ?>
PARSE ERROR
The parse error occurs if there is a syntax mistake in the
script; the output is a Parse errors. The common reason of syntax
errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example:
<?php
echo "C#";
echo "PHP"
echo "C";
?>
TAGS IN PHP:
There are four different pairs of opening and closing tags which can be used in
php. Here is the list of tags.
2. Short open Tags: The short tags starts with "<?" and ends with "?>". Short style
tags are only available when they are enabled in php.ini configuration file on
servers.
Example:
<?
echo "PHP example with short-tags";
?>
3. HTML Script Tags: HTML script tags look like this :
<script language="php">
echo "This is HTML script tags.";
</script>
4. ASP Style Tags: The ASP style tags start with "<%" and ends with
"%>". ASP style tags are only available when they are enabled in
php.ini configuration file on servers.
Example:
<%
echo 'This is ASP like style';
%>
OUTPUT FUNCTIONS IN PHP:
echo statement
• In PHP ‘echo’ statement is a language construct and not a function, so it can be used
without parenthesis.
• But we are allowed to use parenthesis with echo statement when we are using more
than one argument with it.
• The end of echo statement is identified by the semi-colon (‘;’). We can use ‘echo’ to
output strings or variables.
• Displaying Strings: The keyword echo followed by the string to be displayed within
quotes.
<?php
echo "Hello,This is a display string example!";
?>
Output: Hello,This is a display string example!
Displaying Strings as multiple arguments:
We can pass multiple string arguments to the echo statement instead
of single string argument, separating them by comma (‘,’) operator.
For example, if we have two strings say “Hello” and “World” then
we can pass them as (“Hello”, ”World”).
<?php
echo "Multiple ","argument ","string!";
?>
Output: Multiple argument string!
print statement
• The PHP print statement is similar to the echo statement and
can be used alternative to echo at many times.
• It is also language construct and so we may not use
parenthesis:print or print ().
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>
Output: Hello, World!
10+20=30
Comparison between Echo and Print in PHP:
var_dump
Using this function, we can display the value of a variable along
with data type.
Ex:
<?php
$x=100;
$y=”scott”;
var_dump($x);
var_dump($y);
?>
Output: int 100
string(5) scott
printf() :Using this function, we can print variables with
the help of format specifiers.
Example:
<?php
$x=100;
$y=”scott”;
printf(“%d”,$x);
printf(“%s”,$y);
?>
Output: 100 scott
print_r(): Using this function, we can display all elements of
array and properties of object.
Example:
<?php
$x=array(10,20,30);
print_r($x);
?>
Output:
Array
(
[0] 10
[1] 20
[2] 30
)
VARIABLES:
The variable is an identifier that holds data or another variable
and whose value can be changed at the execution time of the script.
Syntax: $variablename=value;
Example:
<?php
define("MSG","Hello world!"); //using case-sensitive
echo MSG;
?>
Output: Hello world!
Example:
<?php
define("MSG","Hello world!"); //using
case-insensitive
echo msg; //error
?>
Output: Hello world!
constant
Define constant using cons keyword in PHP
The const keyword defines constants at compile time. It is a
language construct, not a function. It is a bit faster than
define(). It is always case-sensitive.
Example:
<?php
const MSG="Hello world!";
echo MSG;
?>
Data types
PHP data types are used to hold different types of data or values. PHP
supports the following data types: String, Integer, Float, Boolean,
Array, Object, NULL, and Resource.
Integer:
Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point.
• They can be decimal (base 10), octal (base 8) or hexadecimal
(base16).
• The default base is decimal (base 10).
• The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x.
• The range of integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;
echo $sum;
?>
Output: 704
Float(or)double:
• It can hold numbers containing fractional or decimal part
including positive and negative numbers.
• By default, the variables add a minimum number of decimal
places.
Example:
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
?>
Output: 705.11
String:
• It can hold letters or any alphabets, even numbers are
included.
• These are written within double quotes during declaration.
• The strings can also be written within single quotes but it
will be treated differently while printing variables.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name';
?>
Output: The name of the Geek is Krishna
The name of the geek is $name
NULL:
• These are special types of variables that can hold only one value
i.e., NULL.
• We follow the convention of writing it in capital form, but its
case sensitive.
Example:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>
Boolean:
• Hold only two values, either TRUE or FALSE.
• Successful events will return true and unsuccessful events return
false.
• NULL type values are also treated as false in Boolean.
• If a string is empty then it is also considered as false in boolean
• data type.
Example:
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE
What are PHP Keywords?
PHP keywords are predefined, reserved words in PHP that are used to perform
specific functions. These keywords are reserved by PHP and cannot be used as
variable names, function names, or class names. PHP keywords are case-
insensitive, meaning that they can be written in either upper or lower case
letters.
What is an Exception?
An exception is an unexcepted outcome of a program, which can
be handled by the program itself. Basically, an exception disrupts
the normal flow of the program. But it is different from an error
because an exception can be handled, whereas an error cannot be
handled by the program itself.
Output:
Result of division = 6
Divide by Zero Exception!
Divide by Negative Number Exception!
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
PHP Arithmetic Operators: The arithmetic operators are used to perform common
arithmetical operations, such as addition, subtraction, multiplication etc. Here's a
complete list of PHP's arithmetic operators:
Operator Description 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
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
PHP Assignment Operators: The assignment operators are used to
assign values to variables.Operator Description Example Is The Same As
= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
PHP Comparison Operators: The comparison operators are used to
compare two values in a Boolean fashion.
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and
they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, orthey are not of
the same type
< Less than $x < $y True if $x is less than $y
> Greater than $x > $y True if $x is greater than $y
>= Greater thanor equal to
$x >= $y True if $x is greater than or equal to $y
<= Less than or equal to
$x <= $y True if $x is less than or equal to $y
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
PHP Incrementing and Decrementing Operators
The increment/decrement operators are used to increment/decrement
a variable's value.
++$x Pre-increment Increments $x by one, then returns $x
$x++ Postincrement Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x– Postdecrement Returns $x, then decrements $x by one
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
PHP Logical Operators
The logical operators are typically used to combine conditional
statements.
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
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>
PHP String Operators
There are two operators which are specifically designed for strings.
. Concatenation
.= Concatenation assignment
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
PHP Array Operators
The array operators are used to compare arrays:
+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the
same key/value pairs
=== Identity $x === $y True if $x and $y have the
same key/value pairs in the
same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Ternary operator:
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>