PHP JT 1st Unit
PHP JT 1st Unit
Php Definition:
● The term PHP: Hypertext Preprocessor.
● PHP is a server-side scripting language designed specifically for web
development.
● It is open-source which means it is free to download and use. It is very simple
to learn and use.
● The files have the extension “.php”.
● It is an interpreted language and it does not require a compiler.
What is a PHP File?
● PHP files can contain text, HTML, CSS, JavaScript, and PHP code
● PHP code is executed on the server, and the result is returned to the browser
as plain HTML
● PHP files have extension ".php"
What Can PHP Do?
● PHP can generate dynamic page content
● PHP can create, open, read, write, delete, and close files on the server
● PHP can collect form data
● PHP can send and receive cookies
● PHP can add, delete, modify data in your database
● PHP can be used to control user-access
● PHP can encrypt data
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.
● PHP is easy to learn and runs efficiently on the server side
The History of PHP
1.Conception (1994)
● PHP began as a set of Common Gateway Interface (CGI) binaries written
in the C programming language by Rasmus Lerdorf.
● These were used to track visits to his online resume.
2. PHP/FI (Personal Home Page/Forms Interpreter) (1995)
● Lerdorf extended his work and released the first version of PHP/FI, which
was capable of building simple, dynamic web applications.
● PHP/FI allowed for the embedding of PHP code directly into HTML files,
making it easier to generate dynamic content.
3. PHP/FI 2.0 (1997):
● Andi Gutmans and Zeev Suraski rewrote the PHP/FI parser and formed the
base for PHP 3.
4. PHP 3 (1998):
● PHP 3 introduced the Zend Engine, which greatly improved performance
and allowed for better extensibility.
● PHP 3 was the first version to resemble modern PHP syntax and structure.
● With PHP 3, PHP officially stood for "PHP: Hypertext Preprocessor"
recursively defining its purpose.
5. PHP 4 (2000):
● PHP 4 brought significant improvements, including enhanced performance,
a more stable language core, and better support for object-oriented
programming (OOP).
● It became increasingly popular for building dynamic websites and web
applications.
6.PHP 5 (2004):
● PHP 5 introduced many features, including a more powerful object model
with support for interfaces and exceptions, improved XML support, and
better performance.
● It solidified PHP's place as a mature and robust server-side scripting
language.
7. PHP 6 (Development Abandoned):
● The development of PHP 6 aimed to include native Unicode support.
8. PHP 7 (2015):
● PHP 7 provided a substantial boost to the language's speed and efficiency,
making it more competitive with other modern languages.
9.PHP 8 (2020):
● PHP 8 brought numerous improvements, including the JIT (Just-In-Time)
compiler for further performance enhancements, union types, named
arguments, attributes, and more.
● It continued PHP's evolution as a modern and feature-rich programming
language.
Features of PHP
Here are some of its key features:
1. Easy to Learn:
● PHP syntax is relatively easy to learn, especially for those with a
background in programming languages like C or Perl. Its syntax is similar
to other C-style languages.
2. Open Source:
● PHP is open source, meaning it's free to use and distribute. Its open nature
has led to a large community of developers contributing to its development
and maintenance.
3. Platform Independence:
● PHP runs on various platforms, including Windows, Linux, Unix, Mac OS
X, etc.
● This makes it highly versatile and compatible with different server
environments.
4.Database Integration:
● PHP provides built-in support for many popular databases, including
MySQL, PostgreSQL, SQLite, Oracle, and others.
● This makes it easy to develop dynamic web applications that interact with
databases.
5. Server-Side Scripting:
● PHP is primarily used for server-side scripting, meaning the code is
executed on the server before being sent to the client's browser.
● This allows for dynamic content generation and interaction with databases
and other server-side resources.
6. Wide Adoption:
● PHP is one of the most widely used server-side scripting languages,
powering a significant portion of the web.
● Many popular content management systems (CMS) like WordPress,
Drupal, and Joomla are built using PHP.
7. Extensive Library Support:
● PHP has a vast ecosystem of libraries and frameworks that extend its
functionality and simplify common tasks.
● Frameworks like Laravel, Symfony, and CodeIgniter provide structured
methodologies for building web applications.
8. Flexibility:
● PHP is highly flexible and can be used for various tasks, including
generating dynamic web pages, command-line scripting, and developing
web APIs.
9. Integration Capabilities:
● PHP can be easily integrated with other technologies like HTML, CSS,
JavaScript, XML, JSON, and more, allowing developers to create rich and
interactive web applications.
10. Security Features:
● PHP has various security features built into the language itself, as well as
best practices for securing web applications, such as data validation, input
sanitization, and protection against common security vulnerabilities like
SQL injection and cross-site scripting (XSS).
PHP xampp Installation steps
What is XAMPP?
● XAMPP is an open-source web server solution package. It is mainly
used for web application testing on a localhost web server.
● XAMPP stands for:
○ X = Cross-platform
○ A = Apache Server
○ M = MariaDB
○ P = PHP
○ P = Perl
● Now that you have a better understanding of the XAMPP software, let
us move on to its installation.
● Now that the installation is complete, let’s move ahead to see how to
run a PHP script using the same.
//
2. Inside the demo folder, create a new text file and name it “index.php” and
write the following script.
3. Now, to see the script output, open the XAMPP control panel and start
Apache to host the local webserver, where our script will be running.
4. Now navigate to your browser and type in “localhost/demo/” in the
address bar to view the output.
● The most important fact about PHP is that the programming code can
be embedded directly within an HTML file.
● PHP code is separated from embedded HTML with delimiters. The
delimiters are the <?php and the ?>.
● All PHP is written between these delimiters. An open delimiter <?php
must have a closing delimiter ?>.
● A PHP file will usually have the extension .php
● programming code must be contained within an opening <?php tag
and a matching closing ?> tag in order to differentiate it from the
HTML.
● The programming code within the <?php and the ?> tags is interpreted
and executed, while any code outside the tags is echoed directly out to
the client (browser).
● All statements in PHP must end with a semicolon (;).
<!DOCTYPE html>
<html>
<head>
<title>PHP and HTML</title>
</head>
<body>
<h1><?php echo "Hello, World!"; ?></h1>
<p>Embedding PHP in HTML </p>
</body>
</html>
Output:
● Mixing PHP and HTML: You can mix PHP and HTML within a
single file.
● PHP code is executed on the server, and its output is integrated into the
HTML structure before being sent to the client's browser.
2. Whitespace in HTML and PHP:
● Whitespace in HTML: In HTML, white space (spaces, tabs, line
breaks) is generally insignificant.
● Multiple consecutive spaces are treated as a single space, and line
breaks are usually ignored.
<p>This is a paragraph with multiple spaces and a line break.</p>
Output
This is a paragraph with multiple spaces and a line break.
Output:
PHP Comments:
● PHP comments can be used to describe any line of code so that other
developers can understand the code easily.
● It can also be used to hide any code.
● PHP supports single line and multi line comments.
● These comments are similar to C/C++ and Perl style (Unix shell style)
comments.
● PHP comments can be used to temporarily deactivate particular sections of
code for debugging purposes.
● Say you discover an error originating somewhere in your PHP file — you can
“comment out” a part of the code, rerun the program, and see if the error still
occurs.
● This is much easier (and safer) than deleting lines of code when debugging.
PHP Comment Syntax
● In php, you can add comments to your code to provide explanations, or
temporarily disable certain sections.
● Comments are ignored during the execution of the code.
● PHP has two built-in ways of commenting: single-line comments and
multiline comments. These are written slightly differently.
<?php
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
SENDING DATA TO THE WEB BROWSER
● In PHP, you can send data to the web browser for display using various
techniques.
● The primary function for sending data to the browser is echo.
● Ways to Send Data
1. Using echo Statement:
● The echo statement is one of the most common ways to send data to the
browser.
● It can output one or more strings.
● Example:
<?php
$message = "Hello, World!";
echo $message;
?>
Output:
Output:
1. 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:
● Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
?>
2. PHP Integer
● An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
1. An integer must have at least one digit
2. An integer must not have a decimal point
3. An integer can be either positive or negative
4. 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:
● Example
<?php
$x = 5985;
var_dump($x);
?>
3. 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:
● Example
<?php
$x = 10.365;
var_dump($x);
?>
4. PHP Boolean
● A Boolean represents two possible states: TRUE or FALSE.
● Booleans are often used in conditional testing.
● Example for string values:
<?php
$gender="Male";
echo ($gender=="Male");
?>
● Example for integer value:
<?php
$var=10;
var_dump($var!=10);
echo "<br>";
var_dump($var==10);
?>
5. 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:
● Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
6. 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 that 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.
● Example
<?php
class Car
{
public $color;
public $model;
}
$myCar = new Car;
var_dump($myCar);
?>
$x = "Hello";
var_dump($x);
● If you want to change the data type of an existing variable, but not by
changing the value, you can use casting.
● Casting allows you to change data type on variables:
● Example
$x = 5;
$x = (string) $x;
var_dump($x);
Keyword Description
abstract Declare a class as abstract
and A logical operator
as Used in the foreach loop
break Break out of loops and switch statements
callable A data type which can be executed as a function
case Used in the switch conditional
catch Used in the try..catch statement
class Declare a class
const Define a class constant
continue Jump to the next iteration of a loop
declare Set directives for a block of code
default Used in the switch statement
do Create a do...while loop
echo Output text
else Used in conditional statements
elseif Used in conditional statements
empty Check if an expression is empty
endfor End a for block
endforeach End a foreach block
endif End an if or elseif block
endswitch End a switch block
endwhile End a while block
extends Extends a class or interface
final Declare a class, property or method as final
finally Used in the try...catch statement
for Create a for loop
foreach Create a foreach loop
function Create a function
global Import variables from the global scope
if Create a conditional statement
include Embed code from another file
include_once Embed code from another file
interface Declare an interface
isset Check if a variable exists and is not null
list Assigns array elements into variables
namespace Declares a namespace
new Creates an object
or A logical operator
print Output text
private Declare a property, method or constant as private
protected Declare a property, method or constant as protect
public Declare a property, method or constant as public
require Embed code from another file
require_once Embed code from another file
return Exit a function and return a value
static Declare a property or method as static
switch Create a switch block
throw Throw an exception
try Create a try...catch structure
use Use a namespace
var Declare a variable
while Create a while loop or end a do...while loop
xor A logical operator
yield Used in generator functions
// Define a loop
for ($i = 0; $i < 10; $i++)
{
echo $i;
}
echo "<br>";
// Define a function
function add($x, $y)
{
return $x + $y;
}
echo add($x,$y);
?>
PHP Variables
● A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
● 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)
The following example will output the sum of two variables:
● String
● Integer
● Float (floating point numbers - also called double)
● Boolean
● Array
● Object
● NULL
Example
All three variables get the value "Fruit":
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
Example
Create a constant with a case-sensitive name:
Example
Create a constant with a case-insensitive name:
PHP const Keyword
● You can also create a constant by using the const keyword.
PHP Expressions
Introduction
● Almost everything in a PHP script is an expression.
● Anything that has a value is an expression.
● In a typical assignment statement ($x=100), a literal value, a function or
operands processed by operators is an expression, anything that appears to the
right of assignment operator (=)
Syntax
● $x=100; //100 is an expression
● $a=$b+$c; //b+$c is an expression
● $c=add($a,$b); //add($a,$b) is an expression
● $val=sqrt(100); //sqrt(100) is an expression
● $var=$x!=$y; //$x!=$y is an expression
PHP Operators
● Operators are used to perform operations on variables and values.
Examples:
PHP Assignment Operators
● The PHP assignment operators are used with numeric values to write a value
to a 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.