PDF&Rendition 1 1
PDF&Rendition 1 1
The term PHP is an acronym for – Hypertext Preprocessor. PHP is a server-side scripting
language designed specifically for web development. It is an open-source which means it is
free to download and use. It is very simple to learn and use. The file extension of PHP is
“.php”.
What is PHP?
PHP is a server-side scripting language created primarily for web development but it is also
used as a general-purpose programming language. Unlike client-side languages like
JavaScript, which are executed on the user’s browser, PHP scripts run on the server. The
results are then sent to the client’s web browser as plain HTML.
History of PHP
PHP was introduced by Rasmus Lerdorf in 1994, the first version and participated in the later
versions. It is an interpreted language and it does not require a compiler. The language
quickly evolved and was given the name “PHP,” which initially named was “Personal Home
Page.”
PHP 3 (1998): The first version considered suitable for widespread use.
PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
Characteristics of PHP
PHP code is executed in the server.
It can be integrated with many databases such as Oracle, Microsoft SQL Server,
MySQL, PostgreSQL, Sybase, and Informix.
One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.
The thing that differentiates PHP from the client-side language like HTML is, that
PHP codes are executed on the server whereas HTML codes are directly rendered on
the browser. PHP codes are first executed on the server and then the result is returned
to the browser.
PHP files can support other client-side scripting languages like CSS and JavaScript.
How PHP Works?
The server processes the PHP code. The PHP interpreter parses the script, executes the
code, and generates HTML output.
The server sends the generated HTML back to the client’s browser, which renders the
web page.
This server-side processing allows for dynamic content generation and ensures that sensitive
code is not exposed to the client.
Syntax
<?php
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</html>
Output:
Features of PHP
Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.
Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.
Server-Side Scripting: PHP scripts are executed on the server, generating HTML that
is sent to the client’s browser.
Applications of PHP
PHP is versatile and can be used in a variety of web development scenarios, including:
Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.
Content Management Systems (CMS): Many popular CMSs like WordPress, Joomla,
and Drupal are built with PHP.
E-commerce Platforms: PHP is commonly used to develop e-commerce websites due
to its database integration capabilities.
Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.
API Development: PHP can be used to create APIs for web and mobile applications.
Advantages of PHP
Easy to Learn: The syntax of PHP is quite similar to C and other programming
languages. This makes PHP relatively easy to learn, especially for developers who
already have some programming experience. Beginners find it approachable due to its
straightforward syntax and extensive online resources.
Web Integration: PHP is designed specifically for web development and is embedded
within HTML. It seamlessly integrates with various web technologies, facilitating the
creation of dynamic and interactive web pages.
Database Support: PHP has excellent support for various databases, including
MySQL, PostgreSQL, SQLite, and more. This makes it easy to connect and interact
with databases, a crucial aspect of many web applications.
Disadvantages of PHP
Security Concerns: If not handled properly, PHP code may be susceptible to security
vulnerabilities, such as SQL injection and cross-site scripting (XSS). Developers need to
be cautious and follow best practices to secure PHP applications.
Lack of Modern Features: Compared to newer languages, PHP may lack some modern
language features. However, recent versions of PHP have introduced improvements and
features to address this concern.
Scalability Challenges: PHP can face challenges when it comes to scaling large and
complex applications. Developers may need to adopt additional tools or frameworks to
address scalability issues.
Not Suitable for Large-Scale Applications: While PHP is suitable for small to medium-
sized projects, it might not be the best choice for extremely large and complex
applications where more structured languages might be preferred.
Limited Object-Oriented Programming (OOP) Support: Although PHP supports OOP, its
implementation has been criticized for not being as robust as in some other languages.
However, recent versions have introduced improvements to enhance OOP capabilities.
PHP Variables
PHP Variables are one of the most fundamental concepts in programming. It is used to store
data that can be accessed and manipulated within your code. Variables in PHP are easy to use,
dynamically typed (meaning that you do not need to declare their type explicitly), and
essential for creating dynamic, interactive web applications.
To declare a variable in PHP, you simply assign a value to it using the $ symbol followed by
the variable name. PHP variables are case-sensitive and must start with a letter or an
underscore, followed by any number of letters, numbers, or underscores.
Example
<?php
?>
In PHP, it’s important to follow certain naming conventions for PHP variables to ensure
readability and maintainability:
Start with a Letter or Underscore: Variable names must begin with a letter or an
underscore (_), not a number.
Use Descriptive Names: Variable names should be descriptive of their purpose, e.g.,
$userName, $totalAmount.
Case Sensitivity: PHP variable names are case-sensitive, meaning $name and $Name
are different variables.
Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).
<?php
?>
Objects: Objects are instances of classes, which are templates for creating data
structures with properties and methods.
Variables declared within a function have local scope and cannot be accessed outside the
function. Any declaration of a variable outside the function with the same name (as within the
function) is a completely different variable.
<?php
$num = 60;
function local_var() {
// is a completely different
$num = 50;
local_var();
?>
Output
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the
“global” keyword before the variable to refer to the global variable.
<?php
$num = 20;
function global_var() {
global $num;
global_var();
?>
Output
PHP Arrays
An array stores multiple values in one single variable
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.
By default, the first item has index 0, the second item has item 1, etc.
Example
Create and display an indexed array:
var_dump($cars);
Output:
array(3) {
[0]=>
string(5) "Volvo"
string(4) "Ford"
[2]=>
string(6) "Toyota"
Example
Display the first array item:
echo $cars[0];
Try it Yourself »
Volvo
Change Value
To change the value of an array item, use the index number:
Example
Change the value of the second item:
$cars[1] = "Ford";
var_dump($cars);
Try it Yourself »
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
Example
Display all array items:
Try it Yourself »
Volvo
BMW
Toyota
Index Number
The key of an indexed array is a number, by default the first item is 0 and
the second is 1 etc., but there are exceptions.
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
And if you use the array_push() function to add a new item, the new item will
get the index 3:
Example
array_push($cars, "Ford");
var_dump($cars);
Try it Yourself »
array(4) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
[3]=>
string(4) "Ford"
But if you have an array with random index numbers, like this:
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
Example
array_push($cars, "Ford");
var_dump($cars);
Try it Yourself »
The next array item gets the index 15:
array(4) {
[5]=>
string(5) "Volvo"
[7]=>
string(3) "BMW"
[14]=>
string(6) "Toyota"
[15]=>
string(4) "Ford"
Associative arrays are arrays that use named keys that you assign to them.
var_dump($car);
Try it Yourself »
brand: Ford
model: Mustang
year: 1964
Example
echo $car["model"];
Try it Yourself »
Mustang
Change Value
Example
$car["year"] = 2024;
var_dump($car);
Try it Yourself »
array(3) {
["brand"]=>
string(4) "Ford"
string(7) "Mustang"
["year"]=>
int(2024)
To loop through and print all the values of an associative array, you could use a foreach loop, like
this:
Example
Try it Yourself »
brand: Ford
model: Mustang
year: 1964
The dimension of an array indicates the number of indices you need to select an element.
For a two-dimensional array you need two indices to select an element
Name Stock
Volvo 22
BMW 15
Saab 5
Land Rover 17
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row
and column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
Example
Try it Yourself »
PHP Strings
PHP Strings are one of the most fundamental data types. It is used to handle text data,
manipulate user inputs, generate dynamic content, and much more. PHP provides a wide
array of functions and techniques for working with strings, making it easy to manipulate and
display text.
A string is a sequence of characters used to store and manipulate text data. PHP strings can
include letters, numbers, symbols, and special characters. Strings are a versatile data type,
commonly used for handling input/output, generating dynamic content, and more.
1. Single Quotes
Single quotes are used to define simple strings in PHP. The text within single quotes is treated
literally, meaning special characters and variables are not interpreted.
<?php
// Singlequote strings
echo $site;
Output
Welcome to GeeksforGeeks
<?php
$site = 'GeeksforGeeks';
?>
Output
Welcome to $site
In the above program the echo statement prints the variable name rather than printing the
contents of the variables. This is because single-quotes strings in PHP do not process special
characters. Hence, the string is unable to identify the ‘$’ sign as the start of a variable name.
2. Double Quotes
Unlike single-quote strings, double-quote strings in PHP are capable of processing special
characters.
<?php
?>
Output
Welcome to GeeksforGeeks
Welcome to GeeksforGeeks
In the above program, we can see that the double-quote strings are processing the special
characters according to their properties. The ‘\n’ character is not printed and is considered as
a new line. Also instead of the variable name $site, “GeeksforGeeks” is printed.
<?php
$name = "Krishna";
?>
Output
Some important and frequently used special characters that are used with double-quoted
strings are explained below:
The character begins with a backslash(“\”) is treated as escape sequences and is replaced with
special characters. Here are few important escape sequences.
This function is used to find the length of a string. This function accepts the string as an
argument and returns the length or number of characters in the string.
<?php
?>
Output
20
This function is used to reverse a string. This function accepts a string as an argument and
returns its reversed string.
<?php
?>
Output
!skeeGrofskeeG olleH
This function takes three strings as arguments. The third argument is the original string and
the first argument is replaced by the second one. In other words, we can say that it replaces
all occurrences of the first argument in the original string with the second argument.
<?php
?>
Output
Hello WorldforWorld!
Hello GeeksWorldGeeks!
In the first example, we can see that all occurrences of the word “Geeks” are replaced by
“World” in “Hello GeeksforGeeks!”.
This function takes two string arguments and if the second string is present in the first one, it
will return the starting position of the string otherwise returns FALSE.
<?php
?>
Output
11
bool(false)
We can see in the above program, in the third example the string “Peek” is not present in the
first string, hence this function returns a boolean value false indicating that string is not
present.
echo strtolower($input);
?>
Output
welcome to geeksforgeeks
<?php
echo strtoupper($input);
?>
Output
WELCOME TO GEEKSFORGEEKS
<?php
echo str_word_count($input);
Output
3
PHP Operators
Operators are used to performing operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them, and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1
and 2, performs an addition operation on them to give 3.
Just like any other programming language, PHP also supports various types of operations like
arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables, or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups
of operators:
Arithmetic Operators
Comparison Operators
Assignment Operators
Array Operators
Increment/Decrement Operators
String Operators
Let us now learn about each of these operators in detail.
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.
<?php
$x = 10;
$y = 3;
// Addition
// Subtraction
// Multiplication
// Division
echo "Division: " . ($x / $y) . "\n";
// Modulus
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
Logical $x and
and True if both the operands are true else false
AND $y
Logical $x &&
&& True if both the operands are true else false
AND $y
Logical
! !$x True if $x is false
NOT
Example: This example describes the logical & relational operator in PHP.
<?php
$x = 50;
$y = 30;
if ($x == 50 or $y == 20)
if ($x == 50 || $y == 20)
if (!$z)
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
Comparison Operators: These operators are used to compare two elements and outputs the
result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.
<> Not Equal To $x <> $y Returns True if both the operands are unequal
Less Than or
<= $x <= $y Returns True if $x is less than or equal to $y
Equal To
<?php
$a = 80;
$b = 50;
$c = "80";
// articles.
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
Syntax:
Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.
If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.
<?php
$x = -12;
?>
Output:
Assignment Operators: These operators are used to assign values to different variables, with
or without mid-operations. Here are the assignment operators along with their syntax and
operations, that PHP provides for the operations.
$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y
$x *=
*= Multiply then Assign Simple product same as $x = $x * $y
$y
<?php
$y = 75;
$y = 100;
$y += 200;
$y -= 10;
echo $y, "\n";
$y = 30;
$y *= 20;
$y = 100;
$y /= 5;
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array operation.
$x ==
== Equality Returns true if both has same key-value pair
$y
Non- $x !==
!== Returns True if both are not identical to each other
Identity $y
$x <>
<> Inequality Returns True if both are unequal
$y
<?php
var_dump($x + $y);
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
Increment/Decrement Operators: These are called the unary operators as they work on
single operands. These are used to increment or decrement values.
<?php
$x = 2;
$x = 2;
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x;
?>
Output:
String Operators: This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x;
?>
GeeksforGeeks!!!
GeeksforGeeks!!!
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used to
compare values but instead of returning the boolean results, it returns integer values. If both
the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left
operand is greater, it returns 1. The following table shows how it works in detail:
$x <=>
$x < $y Identical to -1 (right is greater)
$y
$x <=>
$x > $y Identical to 1 (left is greater)
$y
$x >= $x <=> Identical to 1 (if left is greater) or identical to 0 (if both are
$y $y equal)
$x == $x <=>
Identical to 0 (both are equal)
$y $y
$x <=>
$x != $y Not Identical to 0
$y
Example: This example illustrates the use of the spaceship operator in PHP.
<?php
$x = 50;
$y = 50;
$z = 25;
echo "\n";
echo "\n";
$x = "Ram";
$y = "Krishna";
echo "\n";
echo "\n";
Output:
0
1
-1
1
1
-1
Syntax
These operators are called increment and decrement operators respectively. They are unary
operators, needing just one operand and can be used in prefix or postfix manner, although
with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator
decrements by 1). However, when used in assignment expression, prefix
makesincremnt/decrement first and then followed by assignment. In case of postfix,
assignment is done before increment/decrement
Example
Live Demo
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
x = 11 y = 10
Example
Live Demo
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
?>
Output
x = 11 y = 11
Ternary operator has three operands. First one is a logical expression. If it is TRU, second
operand expression is evaluated otherwise third one is evaluated
Example
Live Demo
<?php
$marks=60;
echo $result;
?>
Output
Pass
PHP Control Structures and Loops: if, else, for, foreach, while
Control structures are core features of the PHP language that allow your script to respond
differently to different inputs or situations. This could allow your script to give different
responses based on user input, file contents, or some other data.
As you can see in the above diagram, first a condition is checked. If the condition is true, the
conditional code will be executed. The important thing to note here is that code execution
continues normally after conditional code execution.
if
else
elseif
switch
while
do-while
for
foreach
and more
PHP If Statement
The if construct allows you to execute a piece of code if the expression provided along with it
evaluates to true.
Let's have a look at the following example to understand how it actually works.
<?php
1
$age = 50;
2
{
5
}
7
?>
8
The above example should output the Your age is greater than 30! message since the
expression evaluates to true. In fact, if you want to execute only a single statement, the above
example can be rewritten without brackets, as shown in the following snippet.
1 <?php
?>
6
On the other hand, if you have more than one statement to execute, you must use brackets, as
shown in the following snippet.
<?php
1
if (is_array($user))
2
{
3
?>
8
You always use the else statement in conjunction with an if statement. Basically, you can
define it as shown in the following pseudo-code.
if (expression)
1
{
2
}
4
else
5
{
6
8 }
<?php
1
$age = 50;
2
{
5
}
7
else
8
{
9
}
11
12 ?>
Advertisement
Let's study the basic structure of the elseif statement, as shown in the following pseudo-code.
if (expression1)
1
{
2
}
4
elseif (expression2)
5
{
6
}
8
elseif (expression3)
9
}
12
else
13
{
14
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a default cho
15
}
16
<?php
1
$age = 50;
2
{
5
}
7
{
9
}
11
{
13
}
15
else
16
{
17
}
19
?>
20
As you can see in the above example, we have multiple conditions, so we've used a series
of elseif statements. In the event that all if conditions evaluate to false, it executes the code
provided in the last else statement.
<?php
1
$favourite_site = 'Code';
2
switch ($favourite_site) {
4
case 'Business':
5
case 'Code':
8
break;
10
break;
13
case 'Music':
14
break;
16
case 'Photography':
17
default:
20
}
22
?>
23
As you can see in the above example, we want to check the value of
the $favourite_site variable, and based on the value of the $favourite_site variable, we want
to print a message.
For each value you want to check with the $favourite_site variable, you have to define
the case block. If the value is matched with a case, the code associated with that case block
will be executed. After that, you need to use the break statement to end code execution. If you
don't use the break statement, script execution will be continued up to the last block in the
switch statement.
Finally, if you want to execute a piece of code if the variable's value doesn't match any case,
you can define it under the default block. Of course, it's not mandatory—it's just a way to
provide a default case.
So that's the story of conditional control structures. We'll discuss loops in PHP in the next
section.
Loops in PHP
Loops in PHP are useful when you want to execute a piece of code repeatedly until a
condition evaluates to false. So code is executed repeatedly as long as a condition evaluates
to true, and as soon as the condition evaluates to false, the script continues executing the code
after the loop.
In this section, we'll go through the different types of loops supported in PHP.
Advertisement
while (expression)
1
{
2
Let's have a look at a real-world example to understand how the while loop works in PHP.
<?php
1
$max = 0;
2
echo $i = 0;
3
echo ",";
4
echo $j = 1;
5
echo ",";
6
$result=0;
7
{
10
$result = $i + $j;
11
$i = $j;
13
$j = $result;
14
15
$max = $max + 1;
16
echo $result;
17
echo ",";
18
}
19
?>
20
If you're familiar with the Fibonacci series, you might recognize what the above program
does—it outputs the Fibonacci series for the first ten numbers. The while loop is generally
used when you don't know the number of iterations that are going to take place in a loop.
do
1
// code to execute
3
} while (expression);
4
Let's go through a real-world to understand possible cases where you can use the do-
while loop.
<?php
1
if ($handle)
3
{
4
do
5
{
6
$line = fgets($handle);
7
}
12
fclose($handle);
13
?>
14
In the above example, we're trying to read a file line by line. Firstly, we've opened a file for
reading. In our case, we're not sure if the file contains any content at all. Thus, we need to
execute the fgets function at least once to check if a file contains any content. So we can use
the do-while loop here. do-while evaluates the condition after the first iteration of the loop.
{
2
// code to execute
3
}
4
The expr1 expression is used to initialize variables, and it's always executed.
The expr2 expression is also executed at the beginning of a loop, and if it evaluates to true,
<?php
1
{
3
}
5
?>
6
The above program outputs the square of the first ten numbers. It initializes $i to 1, repeats as
long as $i is less than or equal to 10, and adds 1 to $i at each iteration.
<?php
1
echo $fruit;
5
echo "<br/>";
6
}
7
$employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Engineer');
9
{
11
echo "<br/>";
13
}
14
?>
15
You can also use break to get out of multiple nested loops by supplying a numeric argument.
For example, using break 3 will break you out of 3 nested loops. However, you cannot pass a
variable as the numeric argument if you are using a PHP version greater than or equal to 5.4.
<?php
1
if($j == 2) {
7
break;
8
}
9
}
11
}
12
13
/*
14
Simple Break
15
i=1j=1
16
i=2j=1
17
*/
18
19
if($j == 2) {
24
break 2;
25
}
26
}
28
}
29
30
/*
31
Multi-level Break
32
i=1j=1
33
*/
34
35
Another keyword that can interrupt loops in PHP is continue. However, this only skips the
rest of the current loop iteration instead of breaking out of the loop altogether. Just like break,
you can also use a numerical value with continue to specify how many nested loops it should
skip for the current iteration.
<?php
1
if($j == 2) {
7
continue;
8
}
9
}
12
13
/*
14
Simple Continue
15
i=1j=1j=3j=4j=5
16
i=2j=1j=3j=4j=5
17
*/
18
19
continue 2;
25
}
26
}
28
}
29
30
/*
31
Multi-level Continue
32
i=1j=1
33
i=2j=1
34
*/
35
36
PHP | Functions
A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better understanding of
how functions work. Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information about the statistics from
the boss, performs calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:
User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.
Reusability: If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
While creating a user defined function we need to keep few things in mind:
4. A function name cannot start with a number. It can start with an alphabet or
underscore.
Syntax:
function function_name(){
executable code;
}
Example:
<?php
function funcGeek()
funcGeek();
?>
The information or variable, within the function’s parenthesis, are called parameters. These
are used to hold the values executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma(,) operator. These parameters are used to
accept inputs during runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a parameter is used to hold
those arguments. In common term, both parameter and argument mean the same. We need to
keep in mind that for every parameter, we need to pass its corresponding argument.
Syntax:
Example:
<?php
Output:
The product is 30
PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:
<?php
defGeek("Ram", 15);
// will be considered
defGeek("Adam");
?>
Output:
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.
Functions can also return values to the part of program from where it is called.
The return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The return
statement also marks the end of the function and stops the execution after that and returns the
value.
Example:
<?php
?>
Output:
PHP allows us two ways in which an argument can be passed into a function:
Pass by Value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.
Example:
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
$n = 10;
refGeek($n);
?>
Output:
Attribute Description
name or
It specifies the name of the form and is used to identify individual forms.
id
It specifies the location to which the form data has to be sent when the form
action
is submitted.
It specifies the HTTP method that is to be used when the form is submitted.
method The possible values are get and post. If get method is used, the form data are
visible to the users in the url. Default HTTP method is get.
novalidate It implies the server not to verify the form data when the form is submitted.
Controls used in forms: Form processing contains a set of controls through which the client
and server can communicate and share information. The controls used in forms are:
Textbox: Textbox allows the user to provide single-line input, which can be used for
getting values such as names, search menu and etc.
Textarea: Textarea allows the user to provide multi-line input, which can be used for
getting values such as an address, message etc.
DropDown: Dropdown or combobox allows the user to provide select a value from a
list of values.
Radio Buttons: Radio buttons allow the user to select only one option from the given
set of options.
CheckBox: Checkbox allows the user to select multiple options from the set of given
options.
Buttons: Buttons are the clickable controls that can be used to submit the form.
Creating a simple HTML Form: All the form controls given above is designed by using
the input tag based on the type attribute of the tag. In the below script, when the form is
submitted, no event handling mechanism is done. Event handling refers to the process done
while the form is submitted. These event handling mechanisms can be done by using
javaScript or PHP. However, JavaScript provides only client-side validation. Hence, we can
use PHP for form processing.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
FirstName:
<br>
<br>
LastName
<br>
<br>
Address
<br>
<br>
Email Address:
<br>
<br>
Password:
<br>
</form>
</body>
</html>
Form Validation: Form validation is done to ensure that the user has provided the relevant
information. Basic validation can be done using HTML elements. For example, in the above
script, the email address text box is having a type value as “email”, which prevents the user
from entering the incorrect value for an email. Every form field in the above script is
isset(): This function is used to determine whether the variable or a form control is
having a value or not.
$_GET[]: It is used the retrieve the information from the form control through the
parameters sent in the URL. It takes the attribute given in the url as the parameter.
$_POST[]: It is used the retrieve the information from the form control through the
HTTP POST method. IT takes name attribute of corresponding form control as the
parameter.
Form Processing using PHP: Above HTML script is rewritten using the above mentioned
functions and array. The rewritten script validates all the form fields and if there are no errors,
it displays the received information in a tabular form.
Example:
<?php
if (isset($_POST['submit']))
if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||
(!isset($_POST['password'])) || (!isset($_POST['gender'])))
else
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
?>
<html>
<head>
</head>
<body>
<fieldset>
<?php
if (isset($_POST['submit']))
if (isset($error))
{
echo "<p style='color:red;'>"
. $error . "</p>";
?>
FirstName:
<span style="color:red;">*</span>
<br>
Last Name:
<span style="color:red;">*</span>
<br>
<br>
Address:
<span style="color:red;">*</span>
<br>
<br>
Email:
<span style="color:red;">*</span>
<br>
<br>
Password:
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
<br>
<br>
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
if(!isset($error))
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<thead>";
echo "<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "</tr>";
echo "<tr>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "<tr>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
?>
</body>
</html>
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Some rules to follow for the HTML form above:
The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
First, we will check if the file already exists in the "uploads" folder. If it does, an error
message is displayed, and $uploadOk is set to 0:
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message
is displayed, and $uploadOk is set to 0:
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file
types gives an error message before setting $uploadOk to 0:
In PHP, we can connect to the database using XAMPP web server by using the following
path.
"localhost/phpmyadmin"
Steps in Detail:
Now open your PHP file and write your PHP code to create database and a table in
your database.
o PHP
<?php
$servername = "localhost";
$username = "root";
// Password is empty
$password = "";
$username, $password);
// Check connection
if ($conn->connect_error) {
. $conn->connect_error);
} else {
// Closing connection
$conn->close();
?>
If you want to see your database, just type localhost/phpmyadmin in the web browser and the
database can be found.
Object-oriented style
Procedural style
Parameters:
connection: It is required that specifies the connection to use.
Executing an SQL query: We will understand how we can execute an SQL query with an
example. We will create a database, table and then insert some values into it.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
if ($conn->connect_error) {
} else {
$conn->close();
?>
Output:
Database has been created successfully
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
if ($conn->connect_error) {
)";
$conn->close();
?>
Output:
Table has been created successfully
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
}else{
$conn->close();
?>
Output:
New record created successfully
Note: Since we have used AUTO_INCREMENT, it will automatically insert the record with
“id=1” and for each newly inserted record, it will increase the “id” by one.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
if ($conn->connect_error) {
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
else {
$conn->close();
?>
Output:
id: 1 - Name: XYZ ABC
Sessions in PHP
Sessions allow you to store user information on the server for later use. This is particularly
useful for maintaining user login states, shopping carts, etc.
Starting a Session:
<?php
?>
<?php
$_SESSION['username'] = 'JohnDoe'; // Set a session variable
?>
<?php
?>
Destroying a Session:
<?php
?>
Cookies in PHP
Cookies are used to store data on the client's browser, which can be retrieved later. They are
useful for remembering user preferences, tracking user behavior, etc.
Setting a Cookie:
<?php
setcookie('user', 'JohnDoe', time() + (86400 * 30), "/"); // Set a cookie for 30 days
?>
Accessing a Cookie:
<?php
if(isset($_COOKIE['user'])) {
?>
Deleting a Cookie:
<?php
setcookie('user', '', time() - 3600, "/"); // Delete the cookie by setting its expiration time in the
past
?>
<?php
session_start();
setcookie('theme', 'dark', time() + (86400 * 30), "/"); // Store theme preference in a cookie
?>
<?php
if ($file) {
} else {
?>
“w+” – Opens file for reading and writing both. If file not exist then new file is
created and if file already exists then contents of file is erased.
<?php
echo $content;
fclose($file);
?>
fclose($file);
?>
Writing to Files
You can write to files using the fwrite() function. It writes data to an open file in the specified
mode.
<?php
if ($file) {
fclose($file);
?>
Deleting Files
Use the unlink() function to delete the file in PHP.
<?php
if (file_exists("gfg.txt")) {
unlink("gfg.txt");
} else {
?>
Appending to a File
Appending to a file is adding new data to the end of an existing file rather than overwriting it.
This is useful for keeping logs, preserving user data and other cases in which previous data
should be stored while new entries are added.
In PHP, the fopen() function returns the file pointer of a file used in different opening modes
such as "w" for write mode, "r" read mode and "r+" or "r+" mode for simultaneous read/write
operation, and "a" mode that stands for append mode.
When a file is opened with "w" mode parameter, it always opens a new file. It means that if
the file already exists, its content will be lost. The subsequent fwrite() function will put the
data at the starting position of the file.
Log Files: When documenting events or problems for a website or application, keep
all prior logs.
User Submissions: If users submit comments or forms, you may want to save them
as files.
Data Gathering: You may need to collect data over time while keeping previous
information.
Hello World
TutorialsPoint
PHP Tutorial
Obviously, it is not possible to add new data if the file is opened with "r" mode. However,
"r+" or "w+" mod opens the file in "r/w" mode, but still a fwrite() statement immediately
after opening a file will overwrite the contents.
Example
<?php
$fp = fopen("new.txt", "r+");
fclose($fp);
?>
With this code, the contents of the "new.txt" file will now become −
PHP-MySQL Tutorial
lsPoint
PHP Tutorial
To ensure that the new content is added at the end of the existing file, we need to manually
put the file pointer to the end, before write operation. (The initial file pointer position is at the
0th byte)
The fseek() Function
PHP's fseek() function makes it possible to place the file pointer anywhere you want −
The $whence parameter is from where the offset is counted. Its values are −
Example
So, we need to move the pointer to the end with the fseek() function as in the following code
which adds the new content to the end.
<?php
$fp = fopen("new.txt", "r+");
fseek($fp, 0, SEEK_END);
fclose($fp);
?>
Now check the contents of "new.txt". It will have the following text −
Hello World
TutorialsPoint
PHP Tutorial
PHP-MySQL Tutorial
Append Mode
Instead of manually moving the pointer to the end, the "a" parameter in fopen() function
opens the file in append mode. Each fwrite() statement adds the content at the end of the
existing contents, by automatically moving the pointer to SEEK_END position.
<?php
$fp = fopen("new.txt", "a");
fclose($fp);
?>
One of the allowed modes for fopen() function is "r+" mode, with which the file performs
read/append operation. To read data from any position, you can place the pointer to the
desired byte by fseek(). But, every fwrite() operation writes new content at the end only.
Example
In the program below, the file is opened in "a+" mode. To read the first line, we shift the file
position to 0the position from beginning. However, the fwrite() statement still adds new
content to the end and doesn't overwrite the following line as it would have if the opening
mode "r+" mode.
<?php
$fp = fopen("new.txt", "a+");
fseek($fp, 0, SEEK_SET);
echo $data;
fwrite($fp, "PHP-File Handling");
?>
Thus, we can append data to an existing file if it is opened in "r+/w+" mode or "a/a+" mode
The directory functions allow you to retrieve information about directories and their contents.
Installation
The PHP directory functions are part of the PHP core. No installation is required to use these
functions.
Function Description