Presentation (1)
Presentation (1)
What is PHP?
PHP is an open-source general purpose scripting language, widely used for website
development. It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP:
Hypertext Preprocessor.
PHP is the world’s most popular server-side programming language. Its latest version PHP
8.2.8, released on July 4th, 2023.
Why Learn PHP?
PHP one of the most preferred languages for creating interactive websites and web applications.
PHP scripts can be easily embedded into HTML. With PHP, you can build
A number of PHP based web frameworks have been developed to speed-up the web application
development. The examples are WordPress, Laravel, Symfony etc.
PHP History
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially,
PHP was supposed to be an abbreviation for "Personal Home Page", but it now stands for the
recursive initialism "PHP: Hypertext Preprocessor".
Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI)
programs in C, which he used to maintain in his personal homepage. Later on, He extended them
to work with web forms and to communicate with databases. This implementation of PHP was
"Personal Home Page/Forms Interpreter" or PHP/FI.
Today, PHP is the world’s most popular server-side programming language for building web
applications. Over the years, it has gone through successive revisions and versions.
PHP Versions
PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He
called this suite of scripts "Personal Home Page Tools". It can be regarded as PHP version 1.0.
• In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and
Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version
2.0 status.
• PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans
rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface
for multiple databases, protocols and APIs, object-oriented programming support, and
consistent language syntax.
• PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers,
HTTP sessions, output buffering, secure ways of handling user input and several new language
constructs.
• PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new
object model and dozens of other new features.
• PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng).
Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP
7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations
and Anonymous Classes.
• PHP 8.0 was released on 26 November 2020. This is a major version having many significant
improvements from its previous versions. One standout feature is Just-in-time compilation (JIT)
that can provide substantial performance improvements. The latest version of PHP is 8.2.8,
released on July 4th, 2023.
PHP – Installation
XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The
letter X in the acronym indicates that it is a cross-platform software, available for use on Windows,
Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference
in its functionality.
• Windows − https://sourceforge.net/projects/
• Linux − https://sourceforge.net/projects/
• OS X − https://sourceforge.net/projects/
Features of PHP
PHP is Simple and Easy to Learn
The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for
developers to comprehend, particularly for those who are already familiar with other programming
languages. Web apps can be developed quickly because of its generous pre-defined functions.
A ".php" file may contain HTML, CSS and JavaScript code blocks along with the PHP code. Hence,
the PHP parser must differentiate between the PHP code from the other elements. The PHP parser
interpreter processes this block and returns the response to the browser.
Escaping from HTML
The PHP parser ignores everything outside of a pair of opening and closing tags. Thus, a PHP file
can have mixed content. This allows PHP to be embedded in HTML documents −
A comment in any computer program (such as a PHP program) is a certain explanatory text that
is ignored by the language compiler/interpreter. Its purpose is to help the user understand the
logic used in the program algorithm.
➢ Single-line Comments
➢ Multi-line Comments
Single-line Comments
They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for
inserting a single-line comment in a program.
➢ PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.
➢ Variable names in PHP are case-sensitive.
➢ Variable names follow the same rules as other labels in PHP. A valid variable name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores.
➢ As per the naming convention, "$name", "$rate_of_int", "$Age", "$mark1" are examples
of valid variable names in PHP.
➢ Invalid variable names: "name" (not having $ prefix), "$rate of int" (whitespace not allowed),
"$Age#1" (invalid character #), "$11" (name not starting with alphabet).
Variables are assigned with the "=" operator, with the variable on the left hand side and the
expression to be evaluated on the right.
No Need to Specify the Type of a Variable
PHP is a dynamically typed language. There is no need to specify the type of a variable. On the
contrary, the type of a variable is decided by the value assigned to it. The value of a variable is
the value of its most recent assignment.
Take a look at this following example −
Automatic Type Conversion of Variables
PHP does a good job of automatically converting types from one to another when necessary. In
the following code, PHP converts a string variable "y" to "int" to perform addition with another
integer variable and print 30 as the result.
Take a look at this following example −
Variables are Assigned by Value
In PHP, variables are always assigned by value. If an expression is assigned to a variable, the
value of the original expression is copied into it. If the value of any of the variables in the
expression changes after the assignment, it doesn’t have any effect on the assigned value.
Assigning Values to PHP Variables by Reference
You can also use the way to assign values to PHP variables by reference. In this case, the new
variable simply references or becomes an alias for or points to the original variable. Changes to
the new variable affect the original and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable
which is being assigned (the source variable).
Take a look at this following example −
Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
• Local Variables
• Global Variables
• Static Variables
• Function Parameters
Variable Naming
Rules for naming a variable is −
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but you cannot use characters
like + , - , % , ( , ) . & , etc
There is no size limit for variables.
PHP - Echo/Print
In PHP, both echo and print statements are used to render the output either on the browser or
the PHP console. Both of them are not functions but they are language constructs. Hence,
parentheses should not be used with either of them.
The print statement is similar to echo, but it Both echo and print statements can output
outputs an expression. multiline strings spanning over more than one
lines in the editor. Take a look at the following
example −
A dynamic variable takes the value of a normal variable and treats that as the name of the
variable. In the above example, "good" can be used as the name of a variable by using two dollar
signs "$$" −
We now have two variables: "$a" with contents "good" and "$$a"
with contents "morning". As a result, the following echo
statements will produce the same output −
Example 1 Example 2
Take a look at this following example − Let's take a look at another example −
PHP - Constants
A constant in PHP is a name or an identifier for a simple value. A constant value cannot change
during the execution of the PHP script.
The first five are simple types, and the next two (arrays and objects) are compound types.
The compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
PHP - Type Casting
The term "Type Casting" refers to conversion of one type of data to another. Since PHP is a weakly
typed language, the parser coerces certain data types into others while performing certain
operations. For example, a string having digits is converted to integer if it is one of the operands
involved in the addition operation.
Let's take another example. Here, an
Implicit Type Casting integer variable $a is converted to a string
so that it is concatenated with a string
Here is an example of coercive or implicit type
variable.
casting −
In this case, $b is a
string variable, cast
into an integer to
enable addition. It
will produce the
following output −
Type Casting Operators
To convert an expression of one type to another, you need to put the data type of the latter in
parenthesis before the expression.
You can easily convert a float value to an integer. Take a look at the following example −
➢ If the string starts with digits followed by non-numeric characters, only the initial digits are
considered.
➢ If the string starts with non-numeric characters and the digits are in the middle, the csting
operator returns "0".
Casting to Float Type
You can use either the (float) or (double) casting operator to explicitly convert a variable or
expression to a float.
Casting to String Type
By using a casting operator, any expression evaluating to a floating-point or integer may be cast to
a string type. Few examples are given below −
Casting to Bool Type
Any non-zero number, either integer or float, is cast to true with (bool) operator. An expression
evaluating to "0" returns false. A string is always cast to true.
Take a look at the following example −
PHP - Type Juggling
PHP is known as a dynamically typed language. The type of a variable in PHP changes dynamically.
This feature is called "type juggling" in PHP.
Explicit type declaration of a variable is neither needed nor supported in PHP. Hence the type of
PHP variable is decided by the value assigned to it, and not the other way around.
Example 1
Note that "type casting" in PHP is a little different from "type juggling".
➢ In type juggling, PHP automatically converts types from one to another when necessary. For
➢ On the other hand, type casting takes place when the user explicitly defines the data type in
A string is a sequence of characters, like 'PHP supports string operations.' A string in PHP as an
array of bytes and an integer indicating the length of the buffer. In PHP, a character is the same
as a byte.
To concatenate two string variables together, PHP uses the dot (.) operator −
➢ If a match is found in the string, this function will return the position of the first match.
➢ If no match is found, it will return FALSE.
PHP - Boolean
PHP, "bool" is one of the built-in scalar data types. It is used to express the truth value, and it can
be either True or False. A Boolean literal uses the PHP constants True or False. These constants
are case-insensitive, in the sense, true, TRUE or True are synonymous.
Example
Logical operators (<, >, ==, !=, etc.) return
Boolean values.
Converting a Value to Boolean
For example, using the expression "4 + 5" is equal to 9. Here "4" and "5" are called operands and
Checks if the value of two operands are equal or not, if yes then condition ($a == $b) is not
==
becomes true. true
Checks if the value of two operands are equal or not, if values are not
!= ($a != $b) is true
equal then condition becomes true.
Checks if the value of left operand is greater than the value of right
> ($a > $b) is false
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand,
< ($a < $b) is true
if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
>= ($a >= $b) is false
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of
<= ($a <= $b) is true
right operand, if yes then condition becomes true.
Logical Operators in PHP
Called Logical AND operator. If both the operands are true then condition
and (A and B) is true
becomes true.
Called Logical OR Operator. If any of the two operands are non zero then
or (A or B) is true
condition becomes true.
Called Logical AND operator. If both the operands are non zero then
&& (A && B) is true
condition becomes true.
Called Logical OR Operator. If any of the two operands are non zero then
|| (A || B) is true
condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its
! !(A && B) is false
operand. If a condition is true then Logical NOT operator will make false.
Assignment Operators in PHP
Operator Description Example
Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand value of A + B into C
Add AND assignment operator, It adds right operand to the left C += A is equivalent to
+=
operand and assign the result to left operand C=C+A
Divide AND assignment operator, It divides left operand with the C /= A is equivalent to C
/=
right operand and assign the result to left operand =C/A
• The "." (dot) operator is PHP's concatenation operator. It joins two string operands (characters
of right hand string appended to left hand string) and returns a new string.
• PHP also has the ".=" operator which can be termed as the concatenation assignment operator.
It updates the string on its left by appending the characters of right hand operand.
Array Operators in PHP
Example 1
In the example below, the elements in $arr1 are inserted in $arr2 after a list of its own elements.
Example 2 Example 3
PHP - Null Coalescing Operator
The Null Coalescing operator is one of the many new features introduced in PHP 7. The word
"coalescing" means uniting many things into one. This operator is used to replace the ternary
operation in conjunction with the isset() function.
Example
Let us use the ternary operator to check if a certain variable is set or not with the help of the
isset() function, which returns true if declared and false if not.
The Null Coalescing Operator is represented by the "??" symbol. It acts as a convenient shortcut
to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null;
otherwise it returns its second operand.
Example - The following code reads the name variable from the URL. If indeed there is a value
for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the
user is called Guest.
PHP – Decision Making
• if...else statement − Use this statement if you want to execute a set of code when a condition is true
• elseif statement − Use this statement with the if...else statement to execute a set of code if one of
• switch statement − If you want to select one of many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid long blocks of if..elseif..else code.
PHP - If…Else Statement
Using endif in PHP
PHP code is usually intermixed with HTML script. We can insert HTML code in the if part as well
as the else part in PHP code. PHP offers an alternative syntax for if and else statements. Change
the opening brace to a colon (:) and the closing brace to endif; so that a HTML block can be
added to the if and else part.Open
Example
Let us modify the above code to display
a different message on Sunday, Friday
and other days.
PHP - Switch Statement
The switch statement in PHP can be treated as an alternative to a series of if…else statements
on the same expression
The switch-endswitch Statement
PHP allows the usage of alternative syntax by delimiting the switch construct
with switch-endswitch statements.
PHP – Loop Types
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
The for statement is used when you know how many times you want to execute a statement or a
block of statements.
Syntax of "for" Loop
The syntax of for statement in PHP is similar to the for statement in C language.
The foreach loop in PHP can be used with indexed array as well as associative array. There are
two types of usage syntaxes available −
The value of the expression is checked each time at the beginning of the loop. If
the while expression evaluates to false from the very beginning, the loop won't even be run once.
Even if the expression becomes false during the execution of the block, the execution will not stop
until the end of the iteration.
An array is a data structure that stores one or more data values having some relation among
them, in a single variable. For example, if you want to store the marks of 10 students in a
class, then instead of defining 10 different variables, it’s easy to define an array of 10 length.
There are two ways to declare an array in PHP. One is to use the built-in array() function,
and the other is to use a shorter syntax where the array elements are put inside square
brackets.
• Indexed Array − An array which is a collection of values only is called an indexed array. Each value
is identified by a positional index staring from "0". Values are stored and accessed in linear
fashion.
• Associative Array − If the array is a collection of key-value pairs, it is called as an associative array.
The key component of the pair can be a number or a string, whereas the value part can be of
any type. Associative arrays store the element values in association with key values rather than
in a strict linear index order.
• Multi Dimensional Array − If each value in either an indexed array or an associative array is an
array itself, it is called a multi dimensional array. Values are accessed using multiple indices
Accessing the Array Elements
To access any element from a given array, you can use the array[key] syntax.
Example
For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.
PHP - Indexed Array
An indexed array in PHP may be created either by using the array() function or with the square
bracket syntax.
• Associative arrays are used to implement data structures such as dictionary, maps, trees, etc.
• In PHP, the "=>" symbol is used to establish association between a key and its value.
Accessing the Value with its Key
PHP - Multidimensional Array
A multidimensional array is an array of arrays. In a PHP array, each element can be another array.
Iterating over a 2D Array
Types of Functions
• Built-in functions − PHP’s standard library contains a large number of built-in functions for
string processing, file IO, mathematical computations and more.
• User-defined functions − You can create user-defined functions too, specific to the
requirements of the programming logic.
A function may be invoked from any other function by passing required data
(called parameters or arguments). The called function returns its result back to the calling
environment.
User-defined Functions in PHP
Suppose you want to create a PHP function which will simply write a simple message on your
browser when you will call it.
There are two parts which should be clear to you −
• Creating a PHP Function
• Calling a PHP Function
PHP - Function Parameters
Sometimes the term argument is used for parameter. Actually, the two terms have a certain
difference.
• A parameter refers to the variable used in function’s definition, whereas an argument refers to
the value passed to the function while calling.
• An argument may be a literal, a variable or an expression
• The parameters in a function definition are also often called as formal arguments, and what is
passed is called actual arguments.
• The names of formal arguments and actual arguments need not be same. The value of the
actual argument is assigned to the corresponding formal argument, from left to right order.
• The number of formal arguments defined in the function and the number of actual arguments
passed should be same.
PHP raises
an ArgumentCountError when the
number of actual arguments is less than
formal arguments. However, the
additional actual arguments are ignored
if they are more than the formal
arguments.
Arguments Type Mismatch
PHP is a dynamically typed
language, hence it doesn’t enforce
type checking when copying the
value of an actual argument with a
formal argument. However, if any
statement inside the function body
tries to perform an operation
specific to a particular data type
which doesn’t support it, PHP
raises an exception.
However, PHP is a weakly typed language. It
attempts to cast the variables into
compatible type as far as possible. Hence, if
one of the values passed is a string
representation of a number and the second
is a numeric variable, then PHP casts the
string variable to numeric in order to
perform the addition operation.
PHP - Call by Value
PHP uses the "call by value" mechanism for passing arguments to a function. When a function
is called, the values of actual arguments are copied to the formal arguments of the function’s
definition.
During the execution of the function body, if there is any change in the value of any of
PHP uses the "call by value" mechanism, by default, for passing arguments to a function. If the
arguments within the function are changed, the changes do not reflect outside of the function. To
allow a function to modify its arguments, the "call by reference" mechanism must be used the
following PHP script will help in understanding what references are. Here, $var is a normal string
variable. We declare $var1 as a reference to $var, append "&" symbol to the latter.
When we say that $var1 is an alias or reference of $var, it means any change in its value will
also change the value of $var, and vice versa.
Example
The following example demonstrates how "call by reference" works in PHP −
Calling a PHP Function by Reference
To call a function by reference, you need to declare the formal arguments with name prefixed by
"&" symbol.
Swapping Two Variables
Return by Reference
Just as a function in PHP can accept arguments by reference, it can also return a reference. To
define a function that returns a reference, prefix the name of the function by "&" symbol.
PHP - Default Arguments
a function in PHP may have one or more arguments that have a default value. As a result, such a
function may be called without passing any value to it. If there is no value meant to be passed,
the function will take its default value for processing. If the function call does provide a value, the
default value will be overridden.
Example 2
If you declare arguments with default before arguments without defaults, such function can be
only called if values for both are passed. You cannot have a situation where the first argument
uses the default, and the second using the passed value.
The greeting() function now has $arg1 with default and $arg2 without any default value.
Example 3
Let's define a function percent() that calculates the percentage of marks in three subjects.
Assuming that the marks in each subject are out of 100, the $total argument in the function
definition is given a default value as 300.
However, if the maximum marks in each subject is 50, then you must pass the fourth value to
the function, otherwise the percentage will be calculated out of 300 instead of 150.
PHP - Named Arguments
The feature of Named Arguments has been introduced in PHP with the version 8.0. It is an
extension of the existing mechanism of passing positional arguments to a function while calling.
Passing Named Arguments from an Array
PHP 8.1.0 also introduced another feature that allows using named argument after unpacking
the arguments. Instead of providing values to each argument individually, the values in an array
an be unpacked into the corresponding arguments, using "..." (three dots) before the array.
it is possible to write a function capable of accepting a list of arguments with variable number of
elements. To declare a variable argument list, the name of the argument is prepended by the "..."
(three dots) symbol. The values passed are collected into an array with the argument’s name.
Try changing the size of the passed array and run the program again.
You can use a foreach loop to traverse the array inside the function. The function may have any
positional arguments before the variable length argument. From the received values, the
positional arguments will be populated first, leaving others to be copied to the array.
Variadic Functions
It is possible to process a variable number of arguments to a function, even without the "..."
syntax. PHP has built_in functions like func_num_args(), func_get_arg() and func_get_args(),
which can be used with similar result.
• func_num_args() − Returns the number of arguments passed to the function.
• func_get_arg() − Returns an item from the argument list
• func_get_args() − Returns an array comprising a function's argument list
PHP - Returning Values
array_map
The array_map() is one of the built-in functions. The first argument to this function is a callback
function. There may be one or more arrays as the other arguments. The callback function is
applied to all the elements of arrays. returns an array.
call_user_func
Another example of passing a function to another function is call_user_func(). As the name
suggests, it calls another user defined callback function, and the other arguments are passed to
the callback.
usort
As another example of passing function, we take a look a usort() function. The first
parameter is an array. The array is sorted as per the callback function, which is the second
parameter.
Pass Callback to User-defined
Function
Apart from the above built-in
functions, you can define your own
function that accepts one of the
arguments as another function.
In the example below, we have two
functions, square() and cube(), that
return the square and cube of a
given number.
PHP - Recursive Functions
A recursive function is such a function that calls itself until a certain condition is satisfied. In PHP,
it is possible to defines a recursive function.
PHP - Variable Scope
In PHP, the scope of a variable is the context within which it is defined and accessible to the
extent in which it is accessible.
Based on the scope, a PHP variable can be any of these three types −
• Local Variables
• Global Variables
• Static Variables
A variable in a main script is also made available to any other script incorporated
with include or require statements.
Example - In the following example, a "test.php" script is included in the main script.
However, when the script has a user defined function, any variable inside has a local scope. As a
result, a variable defined inside a function can't be accessed outside. Variables defined outside
(above) the function have a global scope.
Example
Take a look at the following example −
PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a
variable before assigning it any value. The PHP parser tries to cast the variables into compatible
type as far as possible.
For example, if one of the values passed is a string representation of a number, and the second is
a numeric variable, PHP casts the string variable to numeric in order to perform the addition
operation.
PHP can be made to impose stricter rules for type conversion, so that "10" is not implicitly
converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement.
The declare() statement must be the first statement in the PHP code, just after the "<?php" tag.
PHP - Anonymous Functions
PHP allows defining anonymous functions. Normally, when we define a function in PHP, we usually
provide it a name which is used to call the function whenever required. In contrast, an anonymous
function is a function that doesn’t have any name specified at the time of definition. Such a
function is also called closure or lambda function.
Sometimes, you may want a function for one time use only. The most common use of anonymous
functions is to create an inline callback function.
Anonymous Function as a Callback
Anonymous functions are often used as callbacks. Callback functions are used as one of the
arguments of another function.
Example
In this example, we use an anonymous function
inside the usort() function, a built in function that
sorts an array by values using a user-defined
comparison function.
Anonymous Function as Closure
Closure is also an anonymous function that can access the variables outside its scope with the
help of the "use" keyword.
Example
Take a look a the following example −
PHP - Arrow Functions
Arrow functions provide a simpler and more concise syntax for writing anonymous
functions. A keyword "fn" has been introduced for defining arrow functions, instead of the
conventional use of the "function" keyword.
➢ There is only one expression after the "=>" symbol, and its value is the return value of the arrow
function.
➢ The arrow function doesn’t have an explicit return statement.
➢ Like in the anonymous function, the arrow function is assigned to a variable for it to be called.
Using the Arrow Function as a Callback Function
Example
In this example, we use an arrow function inside usort() function, a built_in function that sorts an
array by values using a user-defined comparison function.
Example
Arrow functions capture variables by value automatically, even when nested.
In the following example, an arrow function is defined in the expression part of another arrow
function.
PHP - Superglobals
The PHP parser populates the current script with a number of predefined variables in its global
namespace. The predefined variables are known as "PHP superglobals".
• Any user defined variable declared outside of any function, method, or class also is a global
variable. However, to access it, you need to use the global keyword.
• In contrast, superglobals are always available anywhere in the PHP script, without mentioning them
with the global keyword.
By default, the client browser sends a request for the URL on the server by using the HTTP GET
method. A query string attached to the URL may contain key value pairs concatenated by the "&"
symbol. The $_GET associative array stores these key value pairs.
Save the following script in the document folder of Apache server. If you are using XAMPP server on
Windows, place the script as "hello.php" in the "c:/xampp/htdocs" folder.
Convert the predefined characters "<" (less than) The HTML output of the code above will be (View
and ">" (greater than) to HTML entities: Source):
<?php <!DOCTYPE html>
$str = "This is some <b>bold</b> text."; <html>
echo htmlspecialchars($str); <body>
This is some <b>bold</b> text.
?>
</body>
</html>
PHP - $_FILES
$_FILES is one of the 'superglobal', or automatic global, variables in PHP. It is available in all scopes
throughout a script. The variable $_FILES is an associative array containing items uploaded via HTTP POST
method. The following "test.html" contains a HTML form whose enctype is set to multiform/form-data.
The server-side
PHP script
(upload.php) in
the document
root folder reads
the variables
$_FILES array as
follows −
PHP - $_ENV
$_ENV is a superglobal variable in PHP. It is an associative array that stores all the environment
variables available in the current script.
PHP - $_COOKIE
The PHP superglobal $_COOKIE stores the variables passed to the current PHP script along with
the HTTP request in the form of cookies.
What is a Cookie?
Cookies are text files stored by a server on the client computer and they are kept for tracking
purpose. PHP transparently supports HTTP cookies. Cookies are usually set in an HTTP header.
The server script sends a set of cookies to the browser. It stores this information on the local
machine for future use. Next time, when the browser sends any request to the web server, it sends
those cookies information to the server and the server uses that information to identify the user.
The setcookie() Function
PHP provides the setcookie function to create a cookie object to be sent to the client along with the
HTTP response.
Parameters
• Name − Name of the cookie stored.
• Value − This sets the value of the named variable.
• Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
• Path − Directories for which the cookie is valid.
• Domain − Specifies the domain name in very large domains.
• Security − 1 for HTTPS. Default 0 for regular HTTP.
How to Set Cookies
Take a look at the following example. This script sets a cookie named username if it is not already set.
Example
How to Remove Cookies
To delete a cookie, set the cookie with a date that has already
expired, so that the browser triggers the cookie removal
mechanism.
What is a Session?
A Session is an alternative way to make data accessible across the pages of an entire website. It is
the time duration between the time a user establishes a connection with a server and the time the
connection is terminated. During this interval, the user may navigate to different pages. Many
times, it is desired that some data is persistently available across the pages. This is facilitated
by session variables.
A session creates a file in a temporary directory on the server where the registered session
variables and their values are stored. This data will be available to all the pages on the site during
that visit.
The server assigns a unique SESSIONID to each session. Since HTTP is a stateless protocol, data in
session variables is automatically deleted when the session is terminated.
The session_start() Function
In order to enable access to session data, the session_start() function must be invoked. session_start()
creates a session or resumes the current one based on a session identifier passed via a GET or POST request,
or passed via a cookie.
To read back the value of a session variable, To obtain the list of all the session variables in the
you can use echo/print statements, current session, you can use a foreach loop to
or var_dump() or print_r() functions. traverse the $_SESSION −
Example
The following PHP script renders an HTML
form. The form data is used to create three
session variables. A hyperlink takes the
browser to another page, which reads back
the session variables.
Save this code as "test.php" in the
document root folder, and open it in a client
browser. Enter the data and press
the Submit button.
PHP is a server-side scripting language that is used to create dynamic webpages. It is one of the
most popular programming languages for web development. This chapter aims to let you get
familiarized with certain important concepts of web application development using PHP.
A web-based application is a collection of webpages. A webpage is mainly created with HTML tags.
HTML consists of different HTML tags which are required to define the appearance of page
elements like text, image, table, etc. Hence, HTML essentially creates a static webpage.
A Web application is hosted on a HTTP server with PHP module installed. The browser acts as a
http client, to establish communication with the server, following HTTP protocol.
Using HTML Forms
The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.
An HTML Form is a collection various form controls such as text fields, checkboxes, radio buttons,
etc., with which the user can interact, enter or choose certain data that may be either locally
processed by JavaScript (client-side processing), or sent to a remote server for processing with
the help of server-side programming scripts such as PHP.
One or more form control elements are put inside <form> and </form> tags. The form element is
characterized by different attributes such as name, action, and method.
Form Attributes
Out of the many attributes of the HTML form element, the following attributes are often required
and defined −
Action Attribute
a string representing the URL that processes the form submission. For
example, http://example.com/test.php. To submit the for-data to the same PHP script in which the
HTML form is defined, use the PHP_SELF server variable −
Method Attribute
a string representing the HTTP method to submit the form with. The following methods are the
possible values of method attribute −
• post − The POST method; form data sent as the request body.
• get (default) − The GET; form data appended to the action URL with a "?" separator. Use this
method when the form has no side effects.
Form Example
Let us use these form elements to design a HTML form and send it to a PHP_SELF script
PHP & MySQL
failure.
Selecting a Database
Once you establish a connection with a database server then it is required to select a particular
database where your all the tables are associated.
Creating Database Tables
To create tables in the new database you need to do the same thing as creating the database.
First create the SQL query to create the tables then execute the query using mysql_query()
function.
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and excute those commands.
Consider the following content in sql_query.txt file
Deleting MySQL Database and Table Using PHP
If a database is no longer required then it can be deleted forever. You Its again a matter of issuing one SQL command
can use pass an SQL command to mysql_query to delete a database. through mysql_query function to delete any database
table