WHAT IS PHP
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
• PHP is a server side scripting language that is used to develop Static websites or
Dynamic websites or Web applications.
• PHP scripts can only be interpreted on a server that has PHP installed.
• The client computers accessing the PHP scripts require a web browser only.
What is a Scripting Language?
• A script is a set of programming instructions that is interpreted at runtime.
• A scripting language is a language that interprets scripts at runtime. Scripts
are usually embedded into other software environments.
• The purpose of the scripts is usually to enhance the performance or
perform routine tasks for an application.
• Server side scripts are interpreted on the server while client side scripts are
interpreted by the client application.
• PHP is a server side script that is interpreted on the server
while JavaScript is an example of a client side script that is interpreted by
the client browser. Both PHP and JavaScript can be embedded into HTML
pages.
Scripting Languages
• Server-side scripting languages are - PHP, Node.js, Python, Ruby
on Rails (Ruby), and Java.
•Client-side scripting languages are -
1) Javascript 2) VBScript 3) HTML 4) CSS 5) AJAX
WEB SERVER
• A web server is software and hardware that uses HTTP (Hypertext Transfer Protocol) and other
protocols to respond to client requests made over the World Wide Web.
• The main job of a web server is to display website content through storing, processing and
delivering webpages to users.
• Besides HTTP, web servers also support SMTP (Simple Mail Transfer Protocol) and FTP (File
Transfer Protocol), used for email, file transfer and storage.
• Web server hardware is connected to the internet and allows data to be exchanged with other
connected devices.
• Web server software controls how a user accesses hosted files.
• The web server process is an example of the client/server model. All computers that host
websites must have web server software.
• Web servers are used in web hosting, or the hosting of data for websites and web-based
applications -- or web applications.
• Leading web servers include Apache, Microsoft's Internet Information Services (IIS) and Nginx --
pronounced engine X. Other web servers include Novell's NetWare server, Google Web Server
(GWS) and IBM's family of Domino servers.
WHAT IS 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”
• PHP code may be embedded into HTML code, or it can be used in combination
with various web template systems, web content management system and web
frameworks.
What Can PHP Do? –APPLICATIONS
OF PHP
• 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 is cross platform. 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 MySQL,Postgres, Oracle,
MS SQL Server, ODBC etc.
• PHP is opensource and free. Download it from the official PHP
resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side.
Advantages OR Benefits of PHP
• Simple – PHP is quite easy to learn and get started.
• Fast – PHP websites typically run very fast.
• Stable – PHP is stable since it has been in existence for a long time.
• Open-source and free – PHP is open source and free. It means that you don’t
have to pay a license fee to use PHP to develop software products.
• Community support – PHP has an active online community that helps you
whenever you face an issue.
Disadvantages of PHP : or
Drawbacks
1. It is not that secure due to its open-source.
2. It is not suitable for giant content-based web applications.
3. It has a weak type, which can cause incorrect data and knowledge to users.
4. PHP frameworks got to learn to use PHP built-in functionalities to avoid writing additional code.
5. Using more features of PHP framework and tools cause poor performance of online applications.
6. PHP doesn’t allow change or modification in the core behavior of online applications.
7. While PHP may be a powerful tool supported by an outsized community and plentiful reference documentation,
there are easier programming languages for web apps.
8. 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.
9. It’s highly tough to manage because it’s not competent modular. It already imitates the features of the Java
language.
PHP TAGS
• You can create PHP files without any html tags and that is called Pure PHP file .
• The server interprets the PHP code and outputs the results as HTML code to the
web browsers.
• In order for the server to identify the PHP code from the HTML code, we must
always enclose the PHP code in PHP tags.
• A PHP script starts with <?php and ends with ?>
• PHP is a case sensitive language, “VAR” is not the same as “var”.
• The PHP tags themselves are not case-sensitive, but it is strongly recommended
that we use lower case letter.
• In PHP, keywords (if, else, while), classes, functions, and user-defined functions
are not case-sensitive.
• PHP statements end with a semi colon (;).
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.
Syntax for single-line comments:
// This is a single-line comment
# This is also a single-line comment
Syntax for multiple-line comments:
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
What's new in PHP 7
• PHP 7 is much faster than the previous popular stable release (PHP 5.6)
• PHP 7 has improved Error Handling
• PHP 7 supports stricter Type Declarations for function arguments
• PHP 7 supports new operators (like the spaceship operator:<=>)
PHP Variables
Variables are "containers" for storing information.
Rules for PHP variables:
• In PHP, 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 _ )
• Variables cannot include spaces.
• Keywords cannot be used as variable names.
• Variable names are case-sensitive.
PHP is a Loosely Typed Language
• 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.
So it is called Loosely Typed Language.
PHP variable name is case sensitive
<!DOCTYPE html>
<html>
<body>
<?php
$color = ’red’;
echo "My car is ", $color ,"<br>";//output My car is
red echo "My house is ", $COLOR ,"<br>";// My house
is echo "My boat is ", $coLOR ,"<br>"; // My boat is
?>
</body>
</html>
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:
1) local
2) global
3) static
• A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:
• A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function:
The PHP global keyword
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function).
• PHP also stores all global variables in an array called $GLOBALS[index]. The index
holds the name of the variable. This array is also accessible from within functions
and can be used to update global variables directly.
Global keyword example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y;
// outputs 15 , if we don’t declare global variables in the function; the
output is 10.
?>
Global keyword example
<?php
$life=42;
function meaning()
global $life;
echo 'the meaning of life is '.$life;
meaning();
?>
$GLOBALS[index] example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
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.
• Then, each time the function is called, that variable will still have the information
it contained from the last time the function was called.
STATIC Example
<?php
function myTest()
{ static $x = 0;
echo $x;
$x++;
}
myTest();
echo “<br>”;
myTest();
echo “<br>”;
myTest();
?>
Output
0
1
2
NOTE: IF WE DON’T USE STATIC KEYWORD , THE OUTPUT WILL BE 0 0 0
PHP constants
• Constants are like variables except that once they are defined they cannot be changed or
undefined. A constant is simply a name that holds a single value. As its name implies, the value of
a constant cannot be changed during the execution of the PHP script. Constants are automatically
global across the entire script.
• To define a constant, you use the define() function. The define() function takes the constant’s
name as the first argument and the constant value as the second argument.
• define(name, value, case-insensitive)
define (‘WIDTH’ , ‘15CM’);
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
• By convention, constant names are uppercase. Unlike a variable, the constant name doesn’t start
with the dollar sign. By default, constant names are case-sensitive.
PHP Constant Arrays
•In PHP7, you can create an Array constant using the define() function.
<?php
define("cars", ["Alfa Romeo","BMW","Toyota”]);
echo cars[0];
?>
The const keyword
• PHP provides you with another way to define a constant via the const keyword.
• const CONSTANT_NAME = value;
• define() is a function while the const is a language construct.
• It means that the define() function defines a constant at run-time, whereas the
const keyword defines a constant at compile time.
• Use the define() function if you want to define a constant conditionally or using
an expression.
Constants and Variables -
differences
Differences between constants and variables are
• There is no need to write a dollar sign ($) before a constant, where as in
Variable one has to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be
defined using the define() function.
• Constants may be defined and accessed anywhere without regard to
variable scoping rules.
• Once the Constants have been set, may not be redefined or undefined.
PHP Magic constants
• PHP provides a large number of predefined constants to any script which it runs.
• There are five magical constants that change depending on where they are used.
For example, the value of LINE depends on the line that it's used on in your
script. These special constants are case-insensitive and are as follows −
• LINE The current line number of the file.
• FUNCTION The function name.
• FILE The full path and filename of the file. If used inside an include, the name
of the included file is returned.
• CLASS The class name.
• METHOD The class method name.
PHP echo and print Statements
The differences :
• Echo has no return value while print has a return value of 1 so it can be used in
expressions.
• Echo can take multiple parameters (although such usage is rare) while print can
take one argument.
• Echo is marginally faster than print.
• Echo statement can be used with or without parentheses: echo or echo().
• Print statement can be used with or without parentheses: print or print().
PHP Datatypes
PHP has a total of eight data types which we use to construct our variables −
• Integers − are whole numbers, without a decimal point, like 4195.
• Doubles − are floating-point numbers, like 3.14159 or 49.1.
• Booleans − have only two possible values either true or false.
• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters, like 'PHP supports string operations.'
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can package up both other kinds of
values and functions that are specific to the class.
• Resources − are special variables that hold references to resources external to PHP (such as
database connections).
• The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
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
• The PHP var_dump() function returns the data type and value
• $x=5985;
PHP float
• A float (floating point number) is a number with a decimal point or a number in
exponential form.
•$x = 10.365;
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:
• $x = "Hello world!";
$y = 'Hello world!';
•
PHP Strings
• Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP −
1) Certain character sequences beginning with backslash (\) are replaced with special characters
2) 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 Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• $x = true;
$y = false;
• Booleans are often used in conditional testing.
PHP Array
• An array stores multiple values in one single variable.
• $cars = array("Volvo","BMW","Toyota");
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.
• class Car {
public $color;
public $model;
public function construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
PHP NULL
• 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.
• $x = "Hello world!";
$x = null;
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.
PHP Global Variables - Superglobals
• Some predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special.
• The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
Superglobals
PHP $GLOBALS
• $GLOBALS is a PHP super global variable which is used to access global
variables from anywhere in the PHP script (also from within functions or
methods).
• PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
PHP $_SERVER
• $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations
PHP $_REQUEST
• PHP $_REQUEST is a PHP super global variable which is used to collect data
after submitting an HTML form.
Superglobals
PHP $_POST
• PHP $_POST is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="post". $_POST is also widely used
to pass variables.
PHP $_GET
• PHP $_GET is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="get".
• $_GET can also collect data sent in the URL.
GET Method
• The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ? character.
• The GET method produces a long string that appears in your server logs, in the
browser's Location: box.
• The GET method is restricted to send upto 1024 characters only.
• Never use GET method if you have password or other sensitive information to be
sent to the server.
• GET can't be used to send binary data, like images or word documents, to the
server.
• The data sent by GET method can be accessed using QUERY_STRING environment
variable.
• The PHP provides $_GET associative array to access all the sent information using
GET method.
POST Method
• The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
• The POST method does not have any restriction on data size to be sent.
• The POST method can be used to send ASCII as well as binary data.
• The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information is
secure.
• The PHP provides $_POST associative array to access all the sent information
using POST method.