0% found this document useful (0 votes)
17 views72 pages

PHP Class Notes of Basics

Basic details

Uploaded by

Poornima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views72 pages

PHP Class Notes of Basics

Basic details

Uploaded by

Poornima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

What is PHP

PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.2.14 is
the latest version of PHP, which was released on 28 November.
Some important points need to be noticed about PHP are as followed:

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

Why use PHP

PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.

o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration form.

Applications of PHP

o Server-side web development: It is a development where the program runs on server


dealing with the generation of content of web page.
o Content management systems (CMS): It is a framework already designed by other
programmers and coders on which you can either contribute your knowledge and skills,
or just use those coders’ skills to design your own website or blog
o E-commerce websites: E-commerce, or electronic commerce, refers to the buying and
selling of goods and services over the internet.
o Database-driven applications: It is a software application that relies on a database to
store, manage, and retrieve data. It utilizes a database management system (DBMS) to
organize and manipulate data, enabling efficient data storage, retrieval, and management.
o Web APIs: It is an API as the name suggests, it can be accessed over the web using the
HTTP protocol. It is a framework that helps you to create and develop HTTP based
RESTFUL services.

PHP Features

PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:
Performance:

PHP script is executed much faster than those scripts which are written in other languages such
as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.

Open Source:

PHP source code and software are freely available on the web. You can develop all the versions
of PHP according to your requirement without paying any cost. All its components are free to
download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken automatically at
the time of execution based on the type of data it contains on its value.

Web servers Support:

PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
Security:

PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.

A Helpful PHP Community:

It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

Hello World using PHP.

<html>

<head>
<title>Hello World</title>
</head>

<body>
<?php echo "Hello, World!";?>
</body>

</html>

PHP Echo

PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.
The syntax of PHP echo is given below:

1. void echo (string $arg1 [, string $... ] )

PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:

o echo is a statement, which is used to display the output.


o echo can be used with or without parentheses: echo(), and echo.
o echo does not return any value.
o We can pass multiple strings separated by a comma (,) in echo.
o echo is faster than the print statement.

PHP echo: printing string

1. <?php
2. echo "Hello by PHP echo";
3. ?>

PHP echo: printing multi line string

1. <?php
2. echo "Hello by PHP echo
3. this is multi line
4. text printed by
5. PHP echo statement
6. ";
7. ?>

PHP echo: printing escaping characters

1. <?php
2. echo "Hello escape \"sequence\" characters";
3. ?>

PHP echo: printing variable value

1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>
PHP Print

Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Print statement can be used with or without parentheses: print and print(). Unlike
echo, it always returns 1.

The syntax of PHP print is given below:

1. int print(string $arg)

PHP print statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:

o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.

PHP print: printing string

1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>

PHP print: printing multi line string

1. <?php
2. print "Hello by PHP print
3. this is multi line
4. text printed by
5. PHP print statement
6. ";
7. ?>
PHP print: printing escaping characters

1. <?php
2. print "Hello escape \"sequence\" characters by PHP print";
3. ?>

PHP print: printing variable value

1. <?php
2. $msg="Hello print() in PHP";
3. print "Message is: $msg";
4. ?>
5.
PHP Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:

o As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;

Rules for declaring PHP variable:

o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

PHP Variable: Sum of two variables

<?php

$x=5;

$y=6;

$z=$x+$y;

echo $z;

?>

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.

1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>

PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be accessed. In
other words, "The scope of a variable is the portion of the program within which it is defined and
can be accessed."

PHP has three types of variable scopes:

1. Local variable
2. Global variable
3. Static variable

Local variable

The variables that are declared within a function are called local variables for that function.
These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function. Let's understand the local variables with the help of an
example:

1. <?php
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>

Global variable

The global variables are the variables that are declared outside the function. These variables can
be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or
used outside the function without any keyword. Therefore there is no need to use any keyword to
access a global variable outside the function.

Let's understand the global variables with the help of an example:

1. <?php
2. $name = "Sanaya Sharma"; //Global Variable
3. function global_var()
4. {
5. global $name;
6. echo "Variable inside the function: ". $name;
7. echo "</br>";
8. }
9. global_var();
10. echo "Variable outside the function: ". $name;
11. ?>

Static variable

It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before
the variable to define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:

Example:

1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6. //increment in non-static variable
7. $num1++;
8. //increment in static variable
9. $num2++;
10. echo "Static: ".$num1 ;
11. echo "Non-static: ".$num2 ;
12. }
13. static_var();
14. static_var();
15. ?>

PHP $ and $$ Variables

The $var (single dollar) is a normal variable with the name var that stores any value like string,
integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

To understand the difference better, let's see some examples.


Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>

PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script
except for magic constants, which are not really constants. PHP constants can be defined by 2
ways:

1. Using define() function


2. Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or
changed. They remain constant across the entire program. PHP constants follow the same PHP
variable rules. For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax
of define() function in PHP

1. name: It specifies the constant name.


2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false.
It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>

PHP constant: const keyword

PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const
keyword are case-sensitive.

1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>

Constant() function

There is another way to print the value of constants using constant() function instead of using the
echo statement.

Syntax

The syntax for the following constant function:

1. constant (name)

1. <?php
2. define("MSG", "JavaTpoint");
3. echo MSG, "</br>";
4. echo constant("MSG");
5. //both are similar
6. ?>

7. Constant vs Variables

Constant Variables

Once the constant is defined, it can never be A variable can be undefined as well as
redefined. redefined easily.

A constant can only be defined using define() A variable can be defined by simple
function. It cannot be defined by any simple assignment (=) operator.
assignment.

There is no need to use the dollar ($) sign before To declare a variable, always use the dollar
constant during the assignment. ($) sign before the variable.

Constants do not follow any variable scoping Variables can be declared anywhere in the
rules, and they can be defined and accessed program, but they follow variable scoping
anywhere. rules.

Constants are the variables whose values can't The value of the variable can be changed.
be changed throughout the program.

By default, constants are global. Variables can be local, global, or static.

Magic Constants

Magic constants are the predefined constants in PHP which get changed on the basis of their use.
They start with double underscore (__) and ends with double underscore.

They are similar to other predefined constants but as they change their values with the context,
they are called magic constants.
There are nine magic constants in PHP. In which eight magic constants start and end with double
underscores (__).

__LINE__

__FILE__

__DIR__

__FUNCTION__

__CLASS__

__TRAIT__

__METHOD__

__NAMESPACE__

ClassName::class

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string
PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types

1. resource
2. NULL

PHP Boolean

Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.

Example:

1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>

PHP Integer

Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.

Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31
to 2^31.
Example:

1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>

Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

PHP Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers
with a fractional or decimal point, including a negative or positive sign.

Example:

1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>

Output:

Addition of floating numbers: 73.812

PHP String

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:

Example:

1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>

Output:

Hello Javatpoint
Hello $company

PHP Array

An array is a compound data type. It can store multiple values of same data type in a single
variable.

Example:

1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>

Output:

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object

Objects are the instances of user-defined classes that can store both values and functions. They
must be explicitly declared.

Example:

1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>

Output:

Bike Model: Royal Enfield

PHP Resource

Resources are not the exact data type in PHP. Basically, these are used to store some function
calls or references to external PHP resources. For example - a database call. It is an external
resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

PHP Null

Null is a special data type that has only one value: NULL. There is a convention of writing it in
capital letters as it is case sensitive.

The special type of data type NULL defined a variable with no value.

Example:

1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
PHP Operators

PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators
are used to perform operations on variables or values. For example:

1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:

o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Arithmetic Operators

The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.
Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators

The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".

Operato Name Exampl Explanation


r e

= Assign $a = $b The value of right operand is assigned to the left


operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign
/= Divide then $a /= $b Find quotient same as $a = $a / $b
Assign
(quotient)

%= Divide then $a %= $b Find remainder same as $a = $a % $b


Assign
(remainder)

Bitwise Operators

The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.

Operato Name Exampl Explanation


r e

& And $a & $b Bits that are 1 in both $a and $b are set to 1,
otherwise 0.

| Or (Inclusive $a | $b Bits that are 1 in either $a or $b are set to 1


or)

^ Xor $a ^ $b Bits that are 1 in either $a or $b are set to 0.


(Exclusive or)

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b number of
places

Comparison Operators

Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
Operato Name Exampl Explanation
r e

== Equal $a == $b Return TRUE if $a is equal to $b

=== Identical $a === Return TRUE if $a is equal to $b, and they are of
$b same data type

!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are
not of same data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or $a <= $b Return TRUE if $a is less than or equal $b


equal to

>= Greater than or $a >= $b Return TRUE if $a is greater than or equal $b


equal to

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators

The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation


++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- decrement --$a Decrement the value of $a by one, then return $a

$a-- Return $a, then decrement the value of $a by one

Logical Operators

The logical operators are used to perform bit-level operations on operands. These operators allow
the evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation

and And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

String Operators

The string operators are used to perform the operation on strings. There are two string operators
in PHP, which are given below:
Operato Name Exampl Explanation
r e

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation $a .= $b First concatenate $a and $b, then assign the


and Assignment concatenated string to $a, e.g. $a = $a . $b

Array Operators

The array operators are used in case of array. Basically, these operators are used to compare the
values of arrays.

Operato Name Exampl Explanation


r e

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

!= Inequalit $a != $b Return TRUE if $a is not equal to $b


y

=== Identity $a === Return TRUE if $a and $b have same key/value pair of
$b same type in same order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity

<> Inequalit $a <> $b Return TRUE if $a is not equal to $b


y

Type Operators
The type operator instanceof is used to determine whether an object, its parent and its derived
class are the same type or not. Basically, this operator determines which certain class the object
belongs to. It is used in object-oriented programming.

1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22. ?>

Output:

Charu is a developer.
bool(true) bool(false)

Execution Operators

PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.
Operato Name Exampl Explanation
r e

`` backtick echo Execute the shell command and return the result.
s `dir`; Here, it will show the directories available in current
folder.

Note: Note that backticks (``) are not single-quotes.

Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression,
any error message will be ignored that might be generated by that expression.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

PHP Operators Precedence

Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-


associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) increment/decrement and right


(bool) @ types

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= assignment right


>>= =>

and logical left

xor logical left


or logical left

, many uses (comma) left

PHP Comments

PHP comments can be used to describe any line of code so that other developer can understand
the code easily. It can also be used to hide any code.

PHP supports single line and multi line comments. These comments are similar to C/C++ and
Perl style (Unix shell style) comments.

PHP Single Line Comments

There are two ways to use single line comments in PHP.

o // (C++ style single line comment)


o # (Unix Shell style single line comment)

PHP Multi Line Comments

In PHP, we can comment multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.

PHP If Else

PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

Example

<?php

$num=12;

if($num<100){

echo "$num is less than 100";

}
?>

Output:

12 is less than 100

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.

1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

PHP If-else-if Statement


The PHP if-else-if is a special statement used to combine multiple if?.else
statements. So, we can check multiple conditions using this statement.

1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>

Output:

B Grade

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of
times.

It should be used if the number of iterations is known otherwise use while


loop. This means for loop is used when you already know how many times
you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the
syntax given below:

Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
Example
4. <?php
5. for($n=1;$n<=10;$n++){
6. echo "$n<br/>";
7. }
8. ?>

PHP While Loop


PHP while loop can be used to traverse set of code like for loop. The while
loop executes a block of code repeatedly until the condition is FALSE. Once
the condition gets FALSE, it exits from the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is
checked before entering the loop body. This means that first the condition is
checked. If the condition is true, the block of code will be executed.

1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop.
The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program
several times. If you have to execute the loop at least once and the number
of iterations is not even fixed, it is recommended to use the do-while loop.

It executes the code at least one time always because the condition is
checked after executing the code.

The do-while loop is very much similar to the while loop except the condition
check. The main difference between both loops is that while loop checks the
condition at the beginning, whereas do-while loop checks the condition at
the end of the loop.

1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
8. Difference between while and do-while loop

while Loop do-while loop

The while loop is The do-while loop is


also named also named as exit
as entry control control loop.
loop.

The body of the The body of the


loop does not loop executes at
execute if the least once, even if
condition is false. the condition is
false.

Condition checks Block of statements


first, and then executes first and
block of then condition
statements checks.
executes.

This loop does not Do-while loop use


use a semicolon semicolon to
to terminate the terminate the loop.
loop.

PHP Functions
PHP function is a piece of code that can be reused many times. It can take
input as argument list and return value. There are thousands of built-in
functions in PHP.

In PHP, we can define Conditional function, Function within


Function and Recursive function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.

1. ?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call
by value). But we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a


reference, you need to use ampersand (&) symbol before the argument
name.

Let's see a simple example of call by reference in PHP.

File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

Hello Call By Reference


PHP Call By Value
PHP allows you to call function by value and reference both. In case of PHP
call by value, actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Value' string. But, printing $str variable results
'Hello' only. It is because changes are done in the local variable $str2 only. It
doesn't reflect to $str variable.

1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used
to hold multiple values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the
elements of an array.

Sorting: We can sort the elements of array.


PHP Array Types
There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store
number, string and object in the PHP array. All PHP array elements are
assigned to an index number by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:

1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";

Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]"
;
4. ?>

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"20
0000");

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"20
0000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to
store tabular data in an array. PHP multidimensional array can be
represented in the form of matrix which is represented by row * column.

Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display
following tabular data. In this example, we are displaying 3 rows and 3
columns.

Id Name Salary

1 sonoo 400000

2 john 500000
3 rahul 300000

File: multiarray.php

1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14.}
15. ?>

PHP String
PHP string is a sequence of characters i.e., used to store and manipulate
text. PHP supports only 256-character set and so that it does not offer native
Unicode support. There are 4 ways to specify a string literal in PHP.

1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to
specify a literal backslash (\) use double backslash (\\). All the other
instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.

For Example

Following some examples are given to understand the single quoted PHP
String in a better way:

Example 1

1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>

Output:

Hello text within single quote

Double Quoted
In PHP, we can specify string through enclosing text within double quote
also. But escape sequences and variables will be interpreted using double
quote PHP strings.

Example 1

1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>

Output:
Hello text within double quote

Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax,
an identifier is provided after this heredoc <<< operator, and immediately a
new line is started to write any text. To close the quotation, the string follows
itself and then again that same identifier is provided. That closing identifier
must begin from the new line without any whitespace or tab.

Naming Rules
The identifier should follow the naming rule that it must contain only
alphanumeric characters and underscores, and must start with an
underscore or a non-digit character.

For Example
Valid Example

1. <?php
2. $str = <<<Demo
3. It is a valid example
4. Demo; //Valid code as whitespace or tab is not valid before closing identifier

5. echo $str;
6. ?>

Output:

It is a valid example

Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also
identified with three less than symbols <<< followed by an identifier. But
here identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc follows
the same rule as heredocs.

The difference between newdoc and heredoc is that - Newdoc is a single-


quoted string whereas heredoc is a double-quoted string.

Note: Newdoc works as single quotes.

Example-1:

1. <?php
2. $str = <<<'DEMO'
3. Welcome to javaTpoint.
4. Learn with newdoc example.
5. DEMO;
6. echo $str;
7. echo '</br>';
8.
9. echo <<< 'Demo' // Here we are not storing string content in variabl
e str.
10. Welcome to javaTpoint.
11. Learn with newdoc example.
12.Demo;
13. ?>

Output:

Welcome to javaTpoint. Learn with newdoc example.


Welcome to javaTpoint. Learn with newdoc example.

PHP String Functions


PHP provides various string functions to access and manipulate strings.

A list of PHP string functions are given below.

addcslashes() It is used to return a string with backslashes.


addslashes() It is used to return a string with backslashes.

bin2hex() It is used to converts a string of ASCII


characters to hexadecimal values.

chop() It removes whitespace or other characters


from the right end of a string

chr() It is used to return a character from a


specified ASCII value.

chunk_split() It is used to split a string into a series of


smaller parts.

convert_cyr_string() It is used to convert a string from one Cyrillic


character-set to another.

convert_uudecode() It is used to decode a uuencoded string.

convert_uuencode() It is used to encode a string using the


uuencode algorithm.

count_chars() It is used to return information about


characters used in a string.

crc32() It is used to calculate a 32-bit CRC for a


string.

crypt() It is used to create hashing string One-way.

echo() It is used for output one or more strings.

explode() It is used to break a string into an array.

fprint() It is used to write a formatted string to a


stream.
get_html_translation_ta Returns translation table which is used by
ble() htmlspecialchars() and htmlentities().

hebrev() It is used to convert Hebrew text to visual


text.

hebrevc() It is used to convert Hebrew text to visual


text and new lines (\n) into <br>.

hex2bin() It is used to convert string of hexadecimal


values to ASCII characters.

htmlentities() It is used to convert character to HTML


entities.

html_entity_decode() It is used to convert HTML entities to


characters.

htmlspecialchars() Converts the special characters to html


entities.

htmlspecialchars_decod Converts the html entities back to special


e() characters.

Implode() It is used to return a string from the


elements of an array.

Join() It is the Alias of implode() function.

Levenshtein() It is used to return the Levenshtein distance


between two strings.

Lcfirst() It is used to convert the first character of a


string to lowercase.

localeconv() Get numeric formatting information

ltrim() It is used to remove whitespace from the left


side of a string.

md5() It is used to calculate the MD5 hash of a


string.

md5_files() It is used to calculate MD5 hash of a file.

metaphone() It is used to calculate the metaphone key of


a string.

money_format() It is used to return a string formatted as a


currency string.

nl2br() It is used to insert HTML line breaks in front


of each newline in a string.

nl_langinfo() Query language and locale information

number_format() It is used to format a number with grouped


thousands.

ord() It is used to return ASCII value of the first


character of a string.

parse_str() It is used to parse a query string into


variables.

print() It is used for output one or more strings.

printf() It is used to show output as a formatted


string.

quoted_printable_decod Converts quoted-printable string to an 8-bit


e() string

quoted_printable_encod Converts the 8-bit string back to quoted-


e() printable string

quotemeta() Quote meta characters


rtrim() It is used to remove whitespace from the
right side of a string.

setlocale() It is used to set locale information.

sha1() It is used to return the SHA-1 hash of a


string.

sha1_file() It is used to return the SHA-1 hash of a file.

similar_text() It is used to compare the similarity between


two strings.

Soundex() It is is used to calculate the soundex key of a


string.

sprintf() Return a formatted string

sscanf() It is used to parse input from a string


according to a format.

strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a


string inside another string.

strcmp() Binary safe string comparison (case-


sensitive)

strcoll() Locale based binary comparison(case-


sensitive)

strcspn() It is used to reverses a string.

stripcslashes() It is used to unquote a string quoted with


addcslashes().
stripos() It is used to return the position of the first
occurrence of a string inside another string.

stristr() Case-insensitive strstr

strlen() It is used to return the length of a string.

strncasecmp() Binary safe case-insensitive string


comparison

strnatcasecmp() It is used for case-insensitive comparison of


two strings using a "natural order" algorithm

strnatcmp() It is used for case-sensitive comparison of


two strings using a "natural order" algorithm

strncmp() It is used to compare of the first n


characters.

strpbrk() It is used to search a string for any of a set


of characters.

strripos() It finds the position of the last occurrence of


a case-insensitive substring in a string.

strrpos() It finds the length of the last occurrence of a


substring in a string.

strpos() It is used to return the position of the first


occurrence of a string inside another string.

strrchr() It is used to find the last occurrence of a


string inside another string.

strrev() It is used to reverse a string.

strspn() Find the initial length of the initial segment


of the string
strstr() Find the occurrence of a string.

strtok() Splits the string into smaller strings

strtolower() Convert the string in lowercase

strtoupper() Convert the strings in uppercase

strtr() Translate certain characters in a string or


replace the substring

str_getcsv() It is used to parse a CSV string into an array.

str_ireplace() It is used to replace some characters in a


string (case-insensitive).

str_pad() It is used to pad a string to a new length.

str_repeat() It is used to repeat a string a specified


number of times.

str_replace() It replaces all occurrences of the search


string with the replacement string.

str_rot13() It is used to perform the ROT13 encoding on


a string.

str_shuffle() It is used to randomly shuffle all characters


in a string.

str_split() It is used to split a string into an array.

strcoll() It is locale based string comparison.

strip_tags() It is used to strip HTML and PHP tags from a


string.

str_word_count() It is used to count the number of words in a


string.

substr() Return the part of a string

substr_compare() Compares two strings from an offset up to


the length of characters. (Binary safe
comparison)

substr_count() Count the number of times occurrence of a


substring

substr_replace() Replace some part of a string with another


substring

trim() Remove whitespace or other characters from


the beginning and end of the string.

ucfirst() Make the first character of the string to


uppercase

ucwords() Make the first character of each word in a


string to uppercase

vfprintf() Write a formatted string to a stream

vprintf() Display the output as a formatted string


according to format

vsprintf() It returns a formatted string

wordwrap() Wraps a string to a given number of


characters

PHP File Handling


PHP File System allows us to create file, read file line by line, read file
character by character, write file, append file, delete file and close file.

PHP Open File - fopen()


The PHP fopen() function is used to open a file.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_p


ath = false [, resource $context ]] )

Example

1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.

Syntax

1. ool fclose ( resource $handle )

Example

1. <?php
2. fclose($handle);
3. ?>

PHP Read File - fread()


The PHP fread() function is used to read the content of the file. It accepts two
arguments: resource and file size.

Syntax

1. string fread ( resource $handle , int $length )

Example

1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>

Output

hello php file

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example

1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output

File written successfully

PHP Delete File - unlink()


The PHP unlink() function is used to delete file.

Syntax
1. bool unlink ( string $filename [, resource $context ] )

Example

1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The
fopen() function accepts two arguments: $filename and $mode. The
$filename represents the file to be opended and $mode represents the file
mode for example read-only, read-write, write-only etc.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_p


ath = false [, resource $context ]] )

PHP Open File Mode

Mode Description

r Opens file in read-only mode. It places the file pointer at the beginning of the file.

r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.

w Opens file in write-only mode. It places the file pointer to the beginning of the file an
file to zero length. If file is not found, it creates a new file.

w+ Opens file in read-write mode. It places the file pointer to the beginning of the file an
file to zero length. If file is not found, it creates a new file.

a Opens file in write-only mode. It places the file pointer to the end of the file. If file
creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file
creates a new file.

x Creates and opens file in write-only mode. It places the file pointer at the beginning of
found, fopen() function returns FALSE.

x+ It is same as x but it creates and opens file in read-write mode.

c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is ne
(as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The
positioned on the beginning of the file

c+ It is same as c but it opens file in read-write mode.

PHP Open File Example


1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Read File


PHP provides various functions to read data from file. There are different
functions that allow you to read all file data, read data line by line and read
data character by character.

The available PHP file read functions are given below.

o fread()
o fgets()
o fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two
arguments: file resource and file size.

Syntax
1. string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

Example

1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>

Output

this is first line


this is another line
this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax

1. string fgets ( resource $handle [, int $length ] )

Example

1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
Output

this is first line

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get
all data using fgetc() function, use !feof() function inside the while loop.

Syntax

1. string fgetc ( resource $handle )

Example

1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>

Output

this is first line this is another line this is third line

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write
data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example
ADVERTISEMENT

1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output: data.txt

welcome to php file write

PHP Overwriting File


If you run the above code again, it will erase the previous data of the file and
writes the new data. Let's see the code that writes only new data into
data.txt file.

1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>

Output: data.txt

hello

PHP Append to File


If you use a mode, it will not erase the data of the file. It will write the data at
the end of the file. Visit the next page to see the example of appending data
into file.
PHP Append to File
You can append data into file by using a or a+ mode in fopen() function.
Let's see a simple example that appends data into data.txt file.

Let's see the data of file first.

data.txt

welcome to php file write

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.

Example

1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>

Output: data.txt

welcome to php file write this is additional text appending data

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function
accepts one argument only: file name. It is similar to UNIX C unlink()
function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns
TRUE if file is deleted successfully otherwise FALSE.

Syntax

1. bool unlink ( string $filename [, resource $context ] )


$filename represents the name of the file to be deleted.

PHP Delete File Example


1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>

Output

File deleted successfully

PHP File Upload


PHP allows you to upload single and multiple files through few lines of code
only.

PHP file upload features allows you to upload binary and text files both.
Moreover, you can have the full control over the file to be uploaded through
PHP authentication and file operation functions.

PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of
$_FILES global, we can get file name, file type, file size, temp file name and
errors associated with file.

Here, we are assuming that file name is filename.

$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.

$_FILES['filename']['size']
returns size of the file (in bytes).

$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']
returns error code associated with this file.

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location.
The move_uploaded_file() function checks internally if the file is uploaded
thorough the POST request. It moves the file if it is uploaded through the
POST request.

Syntax

1. bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example


File: uploadform.html

1. <form action="uploader.php" method="post" enctype="multipart/


form-data">
2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
File: uploader.php
1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']
['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_pa
th)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10.?>

PHP Download File


PHP enables you to download file easily using built-in readfile() function. The
readfile() function reads a file and writes it to the output buffer.

PHP readfile() function


Syntax

1. int readfile ( string $filename [, bool $use_include_path = false [, resou


rce $context ]] )

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You


can set it to true to the search the file in the included_path.

ADVERTISEMENT

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.


PHP Download File Example: Text File
File: download1.php

1. <?php
2. $file_url = 'http://www.javatpoint.com/f.txt';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: utf-8");
5. header("Content-disposition: attachment; filename=\"" . basename($fil
e_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Download File Example: Binary File


File: download2.php

1. <?php
2. $file_url = 'http://www.myremoteserver.com/file.exe';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: Binary");
5. header("Content-disposition: attachment; filename=\"" . basename($fil
e_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we
need to use $_GET, for post request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get request
is visible on the URL browser so it is not secured. You can send limited
amount of data through get request.
Let's see a simple example to receive data from get request in PHP.

File: form1.html

1. <form action="welcome.php" method="get">


2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php

1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>

PHP Post Form


Post request is widely used to submit form that have large amount of data
such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it
is secured. You can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html

1. <form action="login.php" method="post">


2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></
td></tr>
4. <tr><td>Password:</td><td> <input type="password" name
="password"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </
td></tr>
6. </table>
7. </form>
File: login.php

1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $p
assword variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>

Output:

PHP WITH OOPS CONCEPT


Object-oriented programming is a programming model organized
around Object rather than the actions and data rather than logic.
Class:
A class is an entity that determines how an object will behave and what the
object will contain. In other words, it is a blueprint or a set of instruction to
build a specific type of object.

In PHP, declare a class using the class keyword, followed by the name of the
class and a set of curly braces ({}).

This is the blueprint of the construction work that is class, and the houses
and apartments made by this blueprint are the objects.

Syntax to Create Class in PHP

1. <?php
2. class MyClass
3. {
4. // Class properties and methods go here
5. }
6. ?>
Important note:
In PHP, to see the contents of the class, use var_dump(). The var_dump()
function is used to display the structured information (type and value) about
one or more variables.

Syntax:
1. var_dump($obj);

Object:
A class defines an individual instance of the data structure. We define a class
once and then make many objects that belong to it. Objects are also known
as an instance.

An object is something that can perform a set of related activities.

Syntax:

1. <?php
2. class MyClass
3. {
4. // Class properties and methods go here
5. }
6. $obj = new MyClass;
7. var_dump($obj);
8. ?>

Example of class and object:

1. <?php
2. class demo
3. {
4. private $a= "hello javatpoint";
5. public function display()
6. {
7. echo $this->a;
8. }
9. }
10.$obj = new demo();
11. $obj->display();
12.?>
13.

Example 2: Use of var_dump($obj);

1. <?php
2. class demo
3. {
4. private $a= "hello javatpoint";
5. public function display()
6. {
7. echo $this->a;
8. }
9. }
10. $obj = new demo();
11. $obj->display();
12. var_dump($obj);
13. ?>

Handling Html Form with PHP

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a
submit button:

ExampleGet your own PHP Server


<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Run Example »
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome John
Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

Run Example »

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing.
You need to validate form data to protect your script from malicious code.

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where keys are
the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These 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.

$_GET is an array of variables passed to the current script via the URL
parameters.

$_POST is an array of variables passed to the current script via the HTTP POST
method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has limits on the
amount of information to send. The limitation is about 2000 characters.
However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive
information!

When to use POST?


Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no
limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part


binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.

Developers prefer POST for sending form data.

Next, lets see how we can process PHP forms the secure way!

You might also like